Skip to content

Instantly share code, notes, and snippets.

@cjbell
Created January 10, 2013 12:10
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 cjbell/4501568 to your computer and use it in GitHub Desktop.
Save cjbell/4501568 to your computer and use it in GitHub Desktop.
Ultra simple state for models.
module CanHaveState
def can_have_state(states = {})
class_eval do
const_set("STATES", states.freeze)
const_set("STATE_CODE_TO_NAME", self::STATES.invert.freeze)
states.each do |type, value|
# Create some helper methods and scopes
scope type, where(:state => value)
define_method "#{ type.to_s }?" do
self.state == value
end
define_method type.to_s do
self.state = value
end
end
def self.states
self::STATES.keys
end
def self.state_code(name)
name = name.to_sym
raise ArgumentError, "#{name} not a valid state" unless self::STATES.has_key?(name)
self::STATES[name]
end
def self.state_name(code)
raise ArgumentError, "#{code} not a valid state" unless self::STATES.has_value?(code)
self::STATE_CODE_TO_NAME[code].to_s
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment