Archive

Archive for the ‘ror’ Category

Rails Hackfest August-07 Results

September 5th, 2007

Rails Hackfest August-07

September 2nd, 2007

I participated in August Rails Hackfest which was a great experience.
You can see the missing August 2007 from the Post Archives. I didn’t post anything last month as I was busy in submitting rails patches. I submitted a lot of patches out of which I got one patch committed to the rails code under changeset 7362 which was about optimizing the code of ActiveRecord Validation validates_presence_of filed under the ticket 9392. Me and kampers got a collaborated patch accepted under the changeset 7383 which was a tiny patch for improving documentation of Action Controller filed under the ticket 9454. Many of my patches got rejected as well by the more experienced Rails Contributors but still, many patches are there to be analyzed by the Rails Core Team.

As I got my code embedded in the Rails Core, I am proud to be recognized as Rails Core Contributor. Tarmo was one of the most active and really appreciable contributor in August Rails Hackfest. Because of this participation I paid very less attention to the other important things including the clients’ projects as well :D. Moreover in the middle of the month I needed to go out to give Rails Training to a really enthusiastic team of a Bangalore based company. It was lovely experience there, but I got out of touch from the Hackfest for those crucial 5 days. After returning back I tried to keep the pace again. I am desperately waiting for the result of the August Rails Hackfest which might get published in a day or two. The first prize is the Entry Pass to the RailsConfEurope. I am looking for submitting more patches now onwards but not with the same pace as of last month, coz I will not be participating in the Hackfest but keeping the spirit of Rails Core Contributor and the pay back policy of open source. I will also be releasing some rails plugins and probably a ruby gem as well this month.

Have you tried this..
[source:ruby]
Object === Class == Class === Object
[/source]

sur hackfest, rails, ror, ruby, rubyonrails

Second delhi.rb meetup - Some Advance Ruby Skills

July 20th, 2007

Hey Everyone,
Vinsol is proudly taking charge to spread Rubyism in delhi and to grow the Ruby & Rails communities here in New Delhi, India. We are organizing delhi.rb meetups around once every month, the meetup is all about ruby and rails as well. The meetup was on 19th July 2007 was our second meetup, first was on 22nd June 2007.

Manik presenting SOLR
Manik presenting SOLR


Me presenting Some Advance Ruby Skills
Me presenting Some Advance Ruby Skills

More photos here.

It was really a nice experience attending the meetup, sharing the ruby/rails thoughts and upcoming features. It helps keeping yourself up-to-date with the latest trends in this technology domain at least in Ruby and Rails(what else m talking except ruby :D). So, there were two presentations in the meetup — first Manik presented Full text search implementation for Rails using SOLR(it was really an interesting presentation, i got SOLR learning for free, thanks Manik :)), second I presented Some Advance Ruby Skills which i am going to share in this post too. Though in the first meetup I presented Caching on RubyOnRails but i haven’t posted here…

Some Advance Ruby Skills

1.) Everything is object

A popular phrase about Ruby, “Everything is Object”. At the root of the ruby it is Object. Everything we define in ruby is object. Even the classes we define are actually object. A class defined with class ClassName; end is actually an object of the class Class.
The Object keeps the record of whatever class or module we define. We can justify it as
[source:ruby]
class Klass
end
Object.constants.include?(”Klass”) # => true
[/source]

2.) module_eval

Use module_eval to define instance and class methods of a class at runtime, when you are outside the class.
example 1
defining an instance method
[source:ruby]
class C
end

C.module_eval do
define_method :wish do
p “hello instance method”
end
end

c = C.new
c.wish # => hello instance method
[/source]
example 2
defining a class method
[source:ruby]
class C
end

C.module_eval do
class << self
define_method :wish do
p "hello class method"
end
end
end

C.wish # => hello class method
[/source]
example 3
another form of using module_eval
when method body is available as a String object
[source:ruby]
class D
class << self
def method_body
ret =<<-EOS
def wish
p "hello, supplied as String object"
end
EOS
end
end

class C
end

c = C.new

c.class.module_eval(D.method_body)

c.wish # => hello, supplied as String object
end
[/source]

3.) alias_method

It is NOT method call delegation but insertion of customized functionalities on a specific method call.
[source:ruby]
class C

def wish
p “hello”
end

end

c = C.new
c.wish # hello

class D

class << self
def keep_some_record
p "I am keeping some records"
end
end

end

# aliasing the wish method

c.class.module_eval do

alias_method :wish_orig, :wish

define_method :wish do
D.keep_some_record
wish_orig
end

end

c.wish # I am keeping some records; hello
[/source]

4.) The Anonymous class

I just presented same a la this post

5.) send

Calling a method when method name is stored as a string object in a variable i.e. you can not see which method to call.
example 1
when method name is simply stored as a String object
[source:ruby]
class C
def wish
p “hello DELHI.rb”
end
end
a = “wish”
c = C.new
c.send(a)
[/source]
example 2
making set method at runtime
[source:ruby]
class C
attr_accessor :name
end

c = C.new

a = “name”

c.send(a + “=”, “SUR MAX”)

p c.send(a)
[/source]
example 3
this is interesting, when attribute name itself is send
[source:ruby]
class C
attr_accessor :send
end

c = C.new

a = “send”

c.__send__(a + “=”, “SUR MAX”)

p c.__send__(a) # => Sur Max
[/source]
well, don’t say “what if attribute name is __send__” :P

6.) The Method class

Methods of the class are objects of the Method class when retrieved with the method method and can be called with the method call.
example 1
anything we define with def-end is an object of the class Method
[source:ruby]
class C
def wish
p “hello”
end
end

c = C.new

m1 = c.method(”wish”)

p m1.class # => Method

m1.call # => hello
[/source]
example 2
method can hold the object’s reference and associated instance variables
[source:ruby]
class C
attr_accessor :name

def initialize(name)
self.name = name.to_s
end

def wish
p “hello ” + name.to_s
end
end

c = C.new(”Sur Max”)

m1 = c.method(”wish”)
m1.call # => hello Sur Max
[/source]
example 3
we are able to let this method object flow throughout the application code and let it available anywhere in the code.
[source:ruby]
class C
attr_accessor :name

def initialize(name)
self.name = name.to_s
end

def wish
p “hello ” + name.to_s
end

def self.supply_wish
c = new(”Sur Max”)
return c.method(”wish”)
end

end

C.supply_wish.call # => hello Sur Max
[/source]

7.) what is “self”

I just presented a la this post

8.) Single Method Delegation - using Forwardable

Allows you to delegate named method calls to other objects.
[source:ruby]
require ‘forwardable’

class C
extend Forwardable

attr_accessor :h

def initialize
@h = {}
end

def_delegator(:@h, :[], :show)
def_delegator(:@h, :[]=, :add)

end

end

c = C.new

c.add(1, “asdf”)

p c.show(1)

p c.h
[/source]
Notice the beauty of ruby here… The methods [], []= of a hash object are usually called as
[source:ruby]
h = {}
h["key"] # this will return the corresponding value
h["key"] = “value” # this will set the “value” corresponding to the “key”
[/source]
BUT in the above delegation code we are calling them as(delegating the method call on them as)
[source:ruby]
h = {}
h.[](”key”) # this will return the corresponding value
h.[]=(”key”, “value”) # this will set the “value” corresponding to the “key”
[/source]

9.) Full class Delegation - using Delegator

Extending an object(instance of Class) with the capabilities of another.
[source:ruby]
require ‘delegate’

class Words < DelegateClass(Array)

def initialize(list = "one two three four")
super(list.split)
end

end

w = Words.new

p w # => ["one", "two", "three", "four"]

p w.length # => 4

[/source]

10.) SimpleDelegator

Write memory optimized code with SimpleDelegator…
[source:ruby]
require ‘delegate’

a = SimpleDelegator.new([10, 20])

old_id = a.__id__

b = a

a.__setobj__(”a new object”) # this is not possible otherwise with the method “replace” which can replace only object of same class on same memory location

new_id = a.__id__

p a # => “a new object”
p b # => “a new object”

p new_id == old_id # => true
[/source]

sur advance_ruby, classes, delegation, delhi.rb, duck typing, metaprogramming, rails, ror, ruby, rubyonrails

How to install RMagick Gem on Linux/Ubuntu

July 4th, 2007

While installing RMagick on Linux, if you are getting errors like this
“GraphicsMagick-config… no configure: error: Can’t install RMagick. Can’t find Magick-config or GraphicsMagick-config program. …”,
below is the solution for this error.

RMagick requires ImageMagick and which further requires loads of dependencies already available to get installed and work properly. I was figuring out of those all, and thank god got a quite simple and elegant way to do all that in just three commands.
First you will have to install imagemagick then libmagick9-dev and then finally you can install rmagick.

Here are the commands…

[source:ruby]
sudo apt-get install imagemagick
sudo apt-get install libmagick9-dev
sudo gem install rmagick
[/source]

sur feisty fawn, gem, linux, rails, ror, ruby, rubyonrails, ubuntu

Plugin: Validate Attributes - validate one or more specific attributes

May 20th, 2007

Hi all,
I found an answer(a tweak) to the question which was pinging my mind while working on my current project that How to validate one or more specific attribute of the model(field of the table i mean)?, as the requirement was to save a record after validating the model’s object through 4 steps ie. 4 different forms. Although i found something in the Rails API to put some step constraints on the validations in the model, but i didn’t find it that much flexible so i wrote a snippet which validates one or more specific attributes and can also save the record on the basis of validating specific attributes. Then i thought to pluginize it, as it might be useful

Check out the plugin Validate Attributes
It provides a simple way to validate specific attribute(s) unlike the function valid? which collectively validates all the attributes.

For more information about the plugin regarding SVN repository, usage, example please visit here

If you like/dislike the plugin or if you have some issue/conflict, please do not forget to post a comment.

sur plugin, rails, ror, ruby, rubyonrails, validate_attributes

Plugin: Simple Captcha - captcha for rubyonrails

February 6th, 2007


Simple Captcha 1.0 released

If you are using an older revision of SimpleCaptcha then it is strongly recommended that update it to the Simple Captcha version 1.0, coz there were certain bugs in the previous release viz. update_attribute, which has been fixed in this release.

Bugs Fixed and Features

  • update_attribute and update_attributes are now working
  • Automated removal of old simple captcha images
  • can be implemented as controller or model based captcha
  • implementation requires a single line of code in view and a single line of code in controller/model
  • customized CSS can be implemented
  • Distortion of images can be selected from three different levels as low, medium or high…
    so that now we can handle the complexities of images
  • Eight different styles of images are available to be selected as your captcha image

check out more details here

sur captcha, plugin, rails, ror, rubyonrails

Sample Rails Application - A demo for the ajax based drag drop tree in rubyonrails

November 26th, 2006

I have provided the source code of the ajax based drag drop tree in rubyonrails in one of my previous posts.
I found some of the people are getting problems to incorporate the code into their running applications so i am providing a sample rails application in which all the code for tree is already been placed well.
However the code written seems to be lagged behind the current trends followed in rails development coz of the fire growth of rails itself, but its simply that when i wrote this tree i was very new to rails so you may find the code looks like an old wine but still tastes good to go with.

CHECK THIS OUT…

Four simple steps to make the tree working…

  1. DOWNLOAD the sample application. (let me know if you are getting any error in downloading the application.)
  2. Create a test database in mysql or modify the file /config/database.yml according to the database and user u need.
  3. Run the command
    ajaxtree> rake db:migrate

    from the application root.

  4. Run the application server by running
    ajaxtree> ruby script/server

    and watch the working tree at http://localhost:3000

sur ajax, ajax tree, drag drop tree, rails, ror, rubyonrails, tree

Javascript Validations and Encryptions — how to use javascript encryptions in rails.

November 14th, 2006

A Quick Review on ENCRYPTIONS
We all are very familiar with the ruby encryptions we usually implement SHA1 or MD5 in our rails applications. In my ongoing project i have been through encryptions in little bit more depth.
MD5 was the most widely used hash algorithm, it converts a string into a 32 characters long hashed key. Then comes the SHA - Secure Hash Algorith. SHA is a series of hash algorithms and its first member is SHA-0 however soon its usage was replaced by the successor SHA-1 and thereafter SHA-0 was never used again. The current members to the SHA series are SHA-1, SHA-224, SHA-256, SHA-384 and the latest SHA-512. At this moment SHA-1 is considered to be the successor of MD5 because of the usage and popularity statistics.
However SHA-224, SHA-256, SHA-384 and SHA-256 are collectively known as SHA-2 series.
Till yet SHA-0 and SHA-1 have been reported attacked but no attack has been found on SHA-2 series.(took from wiki)

Here we will discuss the javascript and ruby based encryptions for SHA-256 only.

Javascript Encryption in Ruby on Rails

If you need to encrypt the password at client side in ror or any other web-based form submission so that the real password string can not reach the server you can you can download the Javascript Encryption files from here. There is all collection of the javascript encryption files available in the above archive. You will not need all of them. Put the file sha256.js in the /public/javascripts/ directory of your rails application.
Now lets take the example of Reset Password where encryption is a must.
This is how you can make your view say reset_password.rhtml


<%= javascript_include_tag 'sha256' %>
<script type="text/javascript">
// <![CDATA[
  function hashPassword() {
  reg = new RegExp(/^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$/);
  if((reg.test($F(’password’)))&&($F(’password’)==$F(’password_confirmation’))){
  document.reset_password.realpass.value = hex_sha256($F(’password’));
  $(’password_confirmation’).value = ”;
  $(’password’).value = ”;
  Element.hide(”reset_password”);
  Element.show(”updating”);
  return true
  }
  else{
  $(’errors_in_pass’).innerHTML = “Password should match confirmation.<br />Password should contain at least one letter and one integer.<br />Password length should be 8 to 40 characters long.<br />”;
  $(’password_confirmation’).value = ”;
  $(’password’).value = ”;
  return false
  }
  }
// ]]>
</script>
<h1>Change Password</h1>
<div style=”display:none;” id=”updating”>Updating Password</div>
<div id = “reset_password”>
<div style = “color:red” id = “errors_in_pass”><%= flash[:notice] %></div>
<% form_for :person, @person, :url => {:action => “reset_password”}, :html => {:name => “reset_password”,:onsubmit => “return hashPassword()”} do |f| %>
<%= hidden_field_tag ‘realpass’ %>
        New Password
        <%= f.password_field :password, :id=>”password”, :class => “field text”, :value=>”" %>
	Confirm New Password
        <%= f.password_field :password_confirmation, :id=>”password_confirmation”, :class => “field text”, :value=>”" %>
	<%= f.submit_tag “Continue” %>
<% end %>
</div>

However it may possible that a user have disabled the javascript of the browser. In that case we will need to add the encryption at server side too. In rubyonrails we can easily handle the SHA256 encryption for let say password by adding the code


require "digest/sha2"

hashed_password = Digest::SHA256.hexdigest("password_string")

in an appropriate position in the controller.

sur encryption, javascript, ror, rubyonrails, validations

Integration Testing in Ruby on Rails — How to maintain sessions while testing in Rails

November 2nd, 2006

Well, its a natural feel to get amazed out of every other delighted feature provided by RubyonRails and so appreciating it before actually talking about the feature in every second post. This line is for those people who have published that the worst thing about rails is that every rails programmer always just focus on the appreciation of rails and not on the framework per se. As i think the reason behind his(let say) perception is that he might not have tried rails and probably in all posts he have been through yet is that he would have got jealous out of gaining popularity of ruby on rails over jsp and asp and else, and therefore he might not be reading the whole post due to which he just remained untouched with the real appreciable features.
Anyhow, here is my post on a fantastic rails feature - Integration Testing…
RoR is the only web application framework which provides an inbuilt high level of testing. Out of the whole testing the most interesting real time testing is Integrations Testing where you can synchronize with the sessions too unlike in the Functional Testing.

Where exactly we should use Integration Testing ?
Whenever we need to test a series of functionalities which belongs to more than one controller , we should go for Integration Testing and not the Functional one.

Since the functional and unit testing are controller and model centric respectively, rails automatically creates the related functional and unit tests files. But as integrations testing is not confined in any criteria of a specific controller or model, we have to create the integrations file manually… Well, nothing is headache in rails. Its a simple pre-written script, all you need is to call that script with a name you like for whole story you wish to test in the integration test.

Here is a real example of Integration Test in Ruby on Rails

Considerations for test…
We will simply test

  • signing in
  • posting a new article
  • deleting an article with xml_http_request (ajax post request)

Create the test file by running


ruby script/generate integration_test initial_features

Make sure that now you have the file /test/integration/initial_features_test.rb. Rails automatically appends _test at the end of the file name.

For god sake Lets start the testing now :-)
Code for the file /test/integration/initial_features_test.rb


require "#{File.dirname(__FILE__)}/../test_helper"

class InitialFeaturesTest < ActionController::IntegrationTest
  fixtures :users, :articles

  def test_initial_features
     user = user_for_test
     user.try_to_signin
     user.signin
     user.post_an_article
     user.delete_an_article_with_xhr
  end

  def user_for_test
    open_session do |user|
      def user.try_to_signin
        assert_nil session[:user] # assert_session_has & _has_no have been deprecated
        get “user/signin”
        assert_response :success
        post “user/signin”, :email=>”test failure string”, :password=>”test failure string”
        assert_nil session[:user]
      end
      def user.signin
        assert_nil session[:user]
        user = users(:first)
        post “user/signin”, :email=>user.email, :password=>user.password
        assert_not_nil session[:user]
        assert_response :redirect
        assert_redirected_to “articles/show”
        # now as the session is set once, we need not to signin again
      end
      def user.post_an_article
        get “articles/show”
        assert_response :success
        assert_template “articles/show”
        user = session[:user]
        articles_count = user.articles.length
        post_via_redirect “article/new”, :title=>”Integration Tetsing in Rails”, :description=>”another relishing rails feature”
        assert_template “articles/show”
        assert_equal articles_count.next, user.reload.articles.length
      end
      def user.delete_an_article_with_xhr
        user = session[:user]
        articles_count = user.articles.length
        xml_http_request “articles/delete”, :id=>articles(:first).id
        assert_equal articles_count-1,user.reload.articles.length
      end
    end
  end

end

Although these are not that high level integration tests that rails can provide but its just an overview on the integration tests. I will explain them soon.

sur integration, rails, ror, rubyonrails, tests

RoR(Ruby on Rails) in India - Ruby on Rails based Indian Company

October 25th, 2006

Ruby on Rails is creating the storms in the web development all over the world. RoR is even capable to challenge Big Caps like Microsoft’s Asp.NET and so everything else in the specific area. World is continuously changing… The current WEB not solely depends on the old,encoded,paid,stressful technologies but the fresh,open-source,free,joyful technologies like Ruby on Rails are now creating the new highways to connect the WEB… What else ?.. Providing a beautiful atmosphere to web-developers. At the moment the whole world of web-development is cherishing the fresh breeze of RoR.
How much of INDIA is delighted by Ruby on Rails ?
Currently, the INDIAN side of Rails is a small community…but growing at a rapid rate. I am proudly working at VINSOL(New Delhi,India), a company full fledged working on rails.
VINSOL is currently holding some good clients for web-development and providing efficient services in Ruby on Rails.

sur India, rails, ror