Created
March 24, 2011 19:52
-
-
Save wxmn/885729 to your computer and use it in GitHub Desktop.
How to Extend Your 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
# create an extensions directory in models | |
# app/models/extensions/popular.rb | |
module Extensions | |
module Popular | |
extend ActiveSupport::Concern | |
# you can include other things here | |
included do | |
include Extensions::OtherCoolStuff | |
# or if you're using Mongoid you can also add fields | |
field :points, :type => Integer, :default => 0 | |
end | |
# include class methods here | |
# like User.most_popular | |
module ClassMethods | |
def most_popular(limit=10) | |
order_by(:points.desc).limit(limit).all | |
end | |
end | |
# include Instance methods | |
# like @user.popularity | |
module InstanceMethods | |
def popularity | |
1+(self.points/100) | |
end | |
end | |
end | |
end | |
# then you can include these is multiple models | |
# so you can have DRY code (Don't Repeat Yourself) | |
class User | |
include Extensions::Popular | |
end | |
class Tags | |
include Extensions::Popular | |
end | |
# now all of the following work: | |
User.most_popular | |
Tag.most_popular | |
@user = User.find(1) | |
@user.popularity #= 12 | |
@tag = Tag.find(1) | |
@tag.popularity #=> 84 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment