Skip to content

Instantly share code, notes, and snippets.

@vinhnglx
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinhnglx/27a73a257cae21fc6818 to your computer and use it in GitHub Desktop.
Save vinhnglx/27a73a257cae21fc6818 to your computer and use it in GitHub Desktop.
Using Metaprogramming to refactor code ref: http://qiita.com/vinhnguyenleasnet/items/3c96930a7b48786e81cf
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
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