Created
September 16, 2012 21:07
-
-
Save regedarek/3734399 to your computer and use it in GitHub Desktop.
Extending models in Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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