Sha256: 02125a5d7bc2539027e902a80e5933857be0fd59c7cdee13be6b9a44fe471662

Contents?: true

Size: 1.26 KB

Versions: 1

Compression:

Stored size: 1.26 KB

Contents

module SimpleStateMachine
  module MongoMapper
    extend ActiveSupport::Concern

    included do
      class_eval do
        class_attribute :states
        self.states = {}
      end
    end

    module ClassMethods
      def state_machine(column, column_states)
        states[column.to_sym] = column_states

        key column, String
        validates_inclusion_of column, :in => column_states

        define_method :"#{column}_revert" do
          write_key column, new? ? states[column].first : send(:"#{column}_was")
        end

        # define a method {state_column}_{state}? for each state
        column_states.each do |state|
          define_method :"#{column}_#{state}?" do
            send(column) === state
          end
        end
      end
    end

    module InstanceMethods
      def initialize(*args)
        super(*args)
        set_initial_state
      end

    private
      def write_key(key, value)
        super(key, states.keys.include?(key) ? value.to_s : value)
      end

      def read_key(key)
        value = super(key)
        value && states.keys.include?(key) ? value.to_sym : value
      end

      def set_initial_state
        states.each do |column, states|
          write_key column, states.first
        end if new?
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
openhood-simple_state_machine-3.0.0 lib/simple_state_machine/mongo_mapper.rb