aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/lib/active_model/state_machine/state.rb
blob: 5851a6fb794f1402e9f3bd2bd7dc8ec54bed74e8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
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
module ActiveModel
  module StateMachine
    class State
      attr_reader :name, :options

      def initialize(machine, name, options={})
        @machine, @name, @options, @display_name = machine, name, options, options.delete(:display)
        machine.klass.send(:define_method, "#{name}?") do
          current_state.to_s == name.to_s
        end
      end

      def ==(state)
        if state.is_a? Symbol
          name == state
        else
          name == state.name
        end
      end

      def call_action(action, record)
        action = @options[action]
        case action
        when Symbol, String
          record.send(action)
        when Proc
          action.call(record)
        end
      end

      def display_name
        @display_name ||= name.to_s.gsub(/_/, ' ').capitalize
      end

      def for_select
        [display_name, name.to_s]
      end
    end
  end
end