Module: SimpleStateMachine::ActiveRecord::ClassMethods

Defined in:
lib/simple_state_machine/active_record.rb

Instance Method Summary collapse

Instance Method Details

#state_machine(column, states) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/simple_state_machine/active_record.rb', line 12

def state_machine(column, states)
  create_empty_state_machine unless respond_to? :states
  self.states[column.to_sym] = states
  validates_inclusion_of column, :in => states
  # should also override getter/setter to convert to strings
  self.class_eval <<-eos
    def #{column.to_s}=(value)
      self[:#{column.to_s}] = value.to_s
    end
    def #{column.to_s}
      self[:#{column.to_s}].to_sym
    end
    def #{column.to_s}_revert
      self[:#{column.to_s}] = self.new_record? ? states[:#{column.to_s}].first.to_s : self.#{column.to_s}_was
    end
  eos

  # define a method {state_column}_{state}? for each state
  states.each do |state|
    self.class_eval <<-eos
      def #{column.to_s}_#{state.to_s}?
        self[:#{column.to_s}] === "#{state.to_s}"
      end
    eos
  end

end