Sha256: d5a5f69e8663081bc038ed463f2b0372170d9703352e726d2bab172d6630ea93

Contents?: true

Size: 1.67 KB

Versions: 3

Compression:

Stored size: 1.67 KB

Contents

module StateMachinable
  module Base
    extend ActiveSupport::Concern

    class_methods do
      def state_class(state)
        "#{self}::#{state.classify}".constantize
      rescue NameError
        nil
      end
    end

    included do
      include Statesman::Machine

      state :initial, :initial => true

      before_transition do |obj, _transition|
        state_class = obj.state_machine.class.state_class(obj.state_machine.current_state)
        if state_class.present? && state_class.respond_to?(:exit)
          state_class.exit(obj)
        end
      end

      after_transition do |obj, transition|
        obj.update(:current_state => transition.to_state)

        state_class = obj.state_machine.class.state_class(transition.to_state)
        if state_class.present? && state_class.respond_to?(:enter)
          state_class.enter(obj)
        end
      end

      def method_missing(name, *args, &block)
        begin
          events = "#{self.class}::EVENTS".constantize.dup
        rescue NameError
          events = []
        end

        events.concat([:ev_before_save, :ev_after_save]).uniq
        clean_name = name.to_s.chomp('!').to_sym

        if events.include?(clean_name)
          state_class = self.class.state_class(self.current_state)
          if state_class.present? && state_class.respond_to?(clean_name)
            state_class.send(clean_name, self.object, *args)
          else
            if name.to_s.last == '!'
              raise StateMachinable::EventNotHandledException.new(:event => clean_name, :state => self.current_state)
            else
              nil
            end
          end
        else
          super
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
state_machinable-2.0.0 lib/state_machinable/base.rb
state_machinable-1.0.1 lib/state_machinable/base.rb
state_machinable-1.0.0 lib/state_machinable/base.rb