Skip to content

Instantly share code, notes, and snippets.

@regedarek
Created September 16, 2012 21:07
Show Gist options
  • Save regedarek/3734399 to your computer and use it in GitHub Desktop.
Save regedarek/3734399 to your computer and use it in GitHub Desktop.
Extending models in Rails
# See http://blog.waxman.me/extending-your-models-in-rails-3 for original post
module Extensions
module Popular
module ClassMethods
def most_popular(limit=10)
order('points desc').limit(limit).all
end
end
def popularity
1+(self.points/100)
end
def self.included(base)
base.extend(ClassMethods)
base.extend(Extensions::OtherCoolStuff)
end
end
end
class User
include Extensions::Popular
end
class Tags
include Extensions::Popular
end
# GTK...
module Extensions
module Ohai
def self.included(base)
base.class_eval do
# share an association (vs. using STI)
belongs_to :parent
# share a scope
scope :recent, where(:created_at => 1.day.ago..Time.now)
end
end
end
end
# Another take, if you want things leaner
module Extensions
module Popular
def popularity
1+(self.points/100)
end
def self.included(base)
def base.most_popular(limit=10)
order('points desc').limit(limit).all
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment