Our Daily Method #6: AR.find(..).each
Geplaatst door Remco van 't Veer di, 12 feb 2008 08:00:00 GMT
AR.find(..).each
Working with ActiveRecord it often bothers me I need to write each
after doing a find-all. I can give find
a block but is just ignored without any warning.
So today no new method but the removal of a method!
class ActiveRecord::Base
def self.find_with_block_sensitivity(*args)
r = find_without_block_sensitivity(*args)
[r].flatten.each {|v| yield v} if block_given?
r
end
class << self
alias_method :find_without_block_sensitivity, :find
alias_method :find, :find_with_block_sensitivity
end
end
Now, instead of:
Article.find(:all).each {|article| puts article.title}
we can write:
Article.find(:all) {|article| puts article.title}
Look ma! No each
! Also works for single object results.