Saturday, May 31, 2008

Give me :five

Yes, give me :five! Enough :first and :all, I want to find :five.

In order to do this, I checked the source code of find :first and find :all in base.rb

base.rb

def find(*args)
options = args.extract_options!
validate_find_options(options)
set_readonly_option!(options)

case args.first
when :first then find_initial(options)
when :all then find_every(options)
else find_from_ids(args, options)
end
end


OK, the next step is easy, override this method by defining a class method of a Model class, let's say, Blog class and add :five argument in.

Use class << self to open the Blog class object and add the find method in to override the original one. You have to implement :first and :all again. Otherwise the "Blog.find :all" will not work.

blogs.rb

class Blog < ActiveRecord::Base
has_many :posts

class << self
def find(*args)
options = args.extract_options!
validate_find_options(options)
set_readonly_option!(options)

case args.first
when :first then find_initial(options)
when :all then find_every(options)
when :five then find :first,
:limit => 1,
:offset => 4 #call :first instead
else find_from_ids(args, options)
end
end
end
end


Now, you can use find :five to retrive the fifth elements:


>>b5=Blog.find :five


Bingo, I got a :five!

No comments: