Last active
August 29, 2015 14:06
-
-
Save vinhnglx/27a73a257cae21fc6818 to your computer and use it in GitHub Desktop.
Using Metaprogramming to refactor code ref: http://qiita.com/vinhnguyenleasnet/items/3c96930a7b48786e81cf
This file contains hidden or 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
class User < ActiveRecord::Base | |
validate_inclusion_of :activation_state, :in => ["pending", "active"] | |
def self.pending_users | |
find :all, :conditions => {:activation_state => 'pending'} | |
end | |
def self.active_users | |
find :all, :conditions => {:activation_state => 'active'} | |
end | |
def pending? | |
self.activation_state == 'pending' | |
end | |
def active? | |
self.activation_state == 'active' | |
end | |
end |
This file contains hidden or 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
class User < ActiveRecord::Base | |
STATES = ['pending', 'active'] | |
validate_inclusion_of :activation_state, :in => STATES | |
class <<self | |
STATES.each do |state| | |
define_method "#{state}_users" do | |
find :all, :conditions => {:activation_state => state} | |
end | |
end | |
end | |
STATES.each do |state| | |
define_method "#{state}?" do | |
self.activation_state == state | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment