Module: SimplyStated

Defined in:
lib/simply_stated.rb

Defined Under Namespace

Modules: ClassMethods Classes: State

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/simply_stated.rb', line 3

def self.included(klass)
  klass.instance_eval do
    extend ClassMethods
    before_validation :transition
    cattr_accessor :states
    cattr_accessor :state_validation_hash
    named_scope :in_state, lambda {|*s| {:conditions => ['state in (?)', s.map(&:to_s)]}}
    named_scope :not_in_state, lambda {|*s| {:conditions => ['state not in (?)', s.map(&:to_s)]}}
    self.state_validation_hash = {}
    self.states = Set.new
  end
end

Instance Method Details

#stateObject



16
# File 'lib/simply_stated.rb', line 16

def state() self[:state].try :to_sym end

#state=(state) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/simply_stated.rb', line 18

def state=(state)
  if self.class.states.include?(state.to_sym)
    self[:state] = state.to_s
    transition
  else
    raise "invalid state #{state}"
  end
end

#transitionObject



27
28
29
30
31
32
# File 'lib/simply_stated.rb', line 27

def transition
  state_before = state
  soft_send :"transition_from_#{state}"
  transition unless state_before == state
  state
end