Module: StatusWorkflow::ClassMethods

Defined in:
lib/status_workflow.rb

Instance Method Summary collapse

Instance Method Details

#status_workflow(transitions) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/status_workflow.rb', line 80

def status_workflow(transitions)
  transitions.inject({}) do |memo, (from_status, to_statuses)|
    to_statuses.each do |to_status|
      memo[to_status] ||= Set.new
      memo[to_status] << from_status
    end
    memo
  end.each do |to_status, from_statuses|
    define_method "enter_#{to_status}!" do
      status_transition! nil, to_status
    end
    define_method "can_enter_#{to_status}?" do |raise_error = false|
      reload
      memo = from_statuses.include? status&.to_sym
      if raise_error and not memo
        raise InvalidTransition, "can't enter #{to_status} from #{status}, expected #{from_statuses.to_a.join('/')}"
      end
      memo
    end
    define_method "enter_#{to_status}_if_possible" do
      begin; send("enter_#{to_status}!"); rescue InvalidTransition; false; end
    end
  end
end