Extending ActiveRecord with count_since
Feb 23rd, 2008 by scott
I just implemented a statistics page for an application and found that I was using this pattern over and over again:
User.count(:conditions => ['created_at> ?', 30.days.ago])
Here's a simple extension I made to ActiveRecord to DRY it up:
module ActiveRecord
class Base
def self.count_since(time_ago)
count(:conditions => ['created_at> ?', time_ago])
end
end
end
class Base
def self.count_since(time_ago)
count(:conditions => ['created_at> ?', time_ago])
end
end
end
Put that snippet in a file in your lib directory. I called mine rails_extensions.rb. Then add require 'rails_extensions' to the bottom of your environment.rb file.
Now you can just do:
User.count_since(30.days.ago)
That's a little cleaner, don't you think?
Scott Nedderman is the founder of Netphase.com, a consulting practice that specializes in building web applications for Internet startups. He is also a vocalist, plays guitar and penny whistle, occasionally performs in musicals, enjoys camping and is a homeschooling father of 6.



