Archive for February, 2007

ActiveRecord finder: Now we can use hash as conditions

Earlier conditions can either be specified as a string or array now in edge rails we can specify hash also. So if we specify conditions as hash then it will generate conditions based on equality with SQL AND.

Example:

User.find(:all, :conditions=>{:first_name => ‘akhil’, :role => ‘admin’})

will generate SQL as “where `first_name` = ‘akhil’ and `role` = ‘admin’”

Also we can have range as condition

Example:

User.find(:all, :conditions => {:access_level => 3..5})

will generate SQL as “where `access_level` BETWEEN 3 AND 5″

This is really helpful modification in ActiveRecord :-)

Delegation in rails

I don’t know why it is not mentioned any where in rails api, it could be very useful for all.

This is straight from rails\activesupport\lib\active_support\core_ext\module\deligation.rb :

Provides a delegate class method to easily expose contained objects’ methods
as your own. Pass one or more methods (specified as symbols or strings)
and the name of the target object as the final :to option (also a symbol
or string). At least one method and the :to option are required.

Delegation is particularly useful with Active Record associations:

class Greeter < ActiveRecord::Base
def hello()
"hello"
end

def goodbye()
"goodbye"
end

end

class Foo < ActiveRecord::Base
belongs_to :greeter
delegate :hello, :to => :greeter
end

Foo.new.hello # => “hello”
Foo.new.goodbye # => NoMethodError: undefined method `goodbye’ for #

Multiple delegates to the same target are allowed:
class Foo < ActiveRecord::Base
delegate :hello, :goodbye, :to => :greeter
end

Foo.new.goodbye # => “goodbye”

Ruby script for creating new rails project and initial SVN import (with ignoring/removing log/other files)

Some days go I wrote a bash script for creating new rails project and initial SVN import (with ignoring/removing log/other files). And I received many comments if I could write a ruby script for this stuff. Hence here is the ruby script for creating new rails project and initial SVN import (with ignoring/removing log/other files). Copy this script to any of your directory as “create_rails_with_subversion.rb” and execute by issuing “ruby create_rails_with_subversion.rb ”
You may need command line subversion for windows.

I have tested it at my windows and linux machine, if it not work for you please let me know.

Also I love to have your comments…. :)