Module: Gexp::StateDefinition::StateMachine::ClassMethods

Defined in:
lib/gexp/state_definition/state_machine.rb

Instance Method Summary collapse

Instance Method Details

#define_state_by(state_configs) ⇒ 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/gexp/state_definition/state_machine.rb', line 12

def define_state_by(state_configs)
  sm            = state_configs
  state_aliases = [ :all, :any ]

  self.instance_eval do
    unless self.methods.include?("state_machine")
      extend ::StateMachine::MacroMethods
    end

    state_machine initial: sm[:initial] do

      # Внешний хук от Handlers
      around_transition :around_handlers

      # State Machine Context
      smc = self

      # State definition
      sm[:states].each do |name, hash|
        smc.state name.to_sym
      #  method = hash
      #  smc.state name do
      #    (methods || []).each do |method|
      #      self.send(method)
      #    end
      #  end
      end

      # Events definition
      sm[:events].each do |name, transitions|

        smc.event name do

          transitions.each do |opts|
            opts[:if] ||= []
            opts[:do] ||= []

            from = opts[:from] || :any
            to   = opts[:to]   || :any

            from = send(from) if state_aliases.include?(from)
            to   = send(to) if state_aliases.include?(to)

            transition from => to, :if => lambda { |item|
              opts[:if].map { |method|
                item.send(method)
              }.all?
            }
            #, :do => lambda { |item|
            #  opts[:do].each { |method|
            #    item.send(method)
            #  }
            #}
          end

        end
      end

      # Before/After transition
      [ :before, :after ].each do |name|

        (sm[name] || []).each do |opts|

          from = opts[:from] || :any
          to   = opts[:to]   || :any

          from = send(from) if state_aliases.include?(from)
          to   = send(to) if state_aliases.include?(to)

          smc.send(:"#{name}_transition", from => to, :do => lambda { |item|
            opts[:do].each do |method|
              item.send(method)
            end
          })

        end
      end

    end
  end
end