Sha256: 3f3899bfcf02e5e1cc8a280af4a38d43102c7b1dedae0a85f201f6b9e2c27557

Contents?: true

Size: 1.34 KB

Versions: 5

Compression:

Stored size: 1.34 KB

Contents

module StateManager
  module Adapters
    module ActiveRecord
      include Base

      def self.matching_ancestors
        %w(ActiveRecord::Base)
      end

      module ResourceMethods

        def self.included(base)
          # Make sure that the model is in a valid state before it is saved
          base.before_validation :_validate_states

          base.extend(ClassMethods)
        end

        def _validate_states
          self.validate_states!
        end

        module ClassMethods
          def state_manager_added(property, klass, options)
            class_eval do
              klass.specification.states.keys.each do |state|
                # The connection might not be ready when defining this code is
                # reached so we wrap in a lamda.
                scope state, lambda {
                  conn = ::ActiveRecord::Base.connection
                  column = conn.quote_column_name klass._state_property
                  query = "#{column} = ? OR #{column} LIKE ?"
                  like_term = "#{state.to_s}.%"
                  where(query, state, like_term)
                }
              end
            end 
          end
        end

      end

      module ManagerMethods

        def write_state(value)
          resource.send :update_attribute, self.class._state_property, value.path
        end

      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
state_manager-0.2.7 lib/state_manager/adapters/active_record.rb
state_manager-0.2.6 lib/state_manager/adapters/active_record.rb
state_manager-0.2.5 lib/state_manager/adapters/active_record.rb
state_manager-0.2.4 lib/state_manager/adapters/active_record.rb
state_manager-0.2.3 lib/state_manager/adapters/active_record.rb