Skip to content

Instantly share code, notes, and snippets.

@gregory
Forked from diegodurs/stateable.rb
Created June 26, 2012 16:14
Show Gist options
  • Save gregory/2996788 to your computer and use it in GitHub Desktop.
Save gregory/2996788 to your computer and use it in GitHub Desktop.
Ruby stateable lib for ActiveRecord class
# Author: Diego d'Ursel
# ---------------------
#
# This simple lib help you to add state to a model without implementing boring functions for each state
# just add macro like "add_state 1, 'mystate'" to the definition of your ActiveRecord model
# this lib require a "state" field in the model
#
# some example of usage:
# ---------------------
# add_state 0, 'inactive'
# add_state 1, 'active'
# add_state 3, 'deleted'
#
# instance.inactive? => true/false
# instance.active! => update_attribute(...)
# instance.active => 1
#
# instance.state => 3
# instance.state_to_s => 'deleted'
# Model.state_active.all
module Stateable
states = {} # need flat scope
# add accessor that return a string
define_method :state_to_s do
states[self.state]
end
ClassMethods = Module.new do
define_method :add_state do |num, str|
# init variables
states[num] = str
# add my_state?
define_method "#{str}?" do
self.state == states.key(str)
end
# add modifier my_state!
define_method "#{str}!" do
self.update_attribute(:state, states.key(str))
end
# return the number behind the string
# this could be moved to a class method instead of instance
define_method "#{str}" do
states.key(str)
end
# add scope state_mystate
self.scope "state_#{str}".to_sym, where("#{self.table_name}.state = ?", states.key(str))
end
end
def self.included(receiver)
receiver.extend ClassMethods
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment