Sha256: 5ae4a1fec479d22301d93f3923afe52aa751c482193e16b53bad54aff0c453e1

Contents?: true

Size: 1.59 KB

Versions: 3

Compression:

Stored size: 1.59 KB

Contents

require_relative "../exceptions"

module Statesman
  module Adapters
    class Mongoid
      attr_reader :transition_class
      attr_reader :parent_model

      def initialize(transition_class, parent_model, observer)
        @transition_class = transition_class
        @parent_model = parent_model
        @observer = observer
        unless transition_class_hash_fields.include?('statesman_metadata')
          raise UnserializedMetadataError, metadata_field_error_message
        end
      end

      def create(from, to, metadata = {})
        transition = transitions_for_parent.build(to_state: to,
                                                  sort_key: next_sort_key,
                                                  statesman_metadata: metadata)

        @observer.execute(:before, from, to, transition)
        transition.save!
        @observer.execute(:after, from, to, transition)
        @observer.execute(:after_commit, from, to, transition)
        @last_transition = nil
        transition
      end

      def history
        transitions_for_parent.asc(:sort_key)
      end

      def last
        @last_transition ||= history.last
      end

      private

      def transition_class_hash_fields
        transition_class.fields.select { |k, v| v.type == Hash }.keys
      end

      def metadata_field_error_message
        "#{transition_class.name}#statesman_metadata is not of type 'Hash'"
      end

      def transitions_for_parent
        @parent_model.send(@transition_class.collection_name)
      end

      def next_sort_key
        (last && last.sort_key + 10) || 0
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
statesman-0.6.0 lib/statesman/adapters/mongoid.rb
statesman-0.5.0 lib/statesman/adapters/mongoid.rb
statesman-0.4.0 lib/statesman/adapters/mongoid.rb