Sha256: dd3261b137dc1fe583947bddb36e581bc263f8f5fe511788555a4a301685ca4e

Contents?: true

Size: 1.56 KB

Versions: 2

Compression:

Stored size: 1.56 KB

Contents

module StateMachinable::BaseStateMachine
  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_column(: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
      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 EventNotHandledException.new(:event => clean_name, :state => self.current_state)
          else
            nil
          end
        end
      else
        super
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
state_machinable-0.0.3 lib/state_machinable/base_state_machine.rb
state_machinable-0.0.2 lib/state_machinable/base_state_machine.rb