Sha256: cedaf63c3aa4264fb9bd67a7721be4ca635d281aba0312da07854a0ede3ff359

Contents?: true

Size: 1.5 KB

Versions: 2

Compression:

Stored size: 1.5 KB

Contents

module Interactor
  module Schema
    class Context
      def self.build(context = {}, schema = [])
        self === context ? context : new(schema).tap do |instance|
          instance.assign(context)
        end
      end

      def initialize(schema = [])
        @schema = schema
        @table = {}
        define_schema_methods(schema)
      end

      def [](key)
        @table[key]
      end

      def assign(context)
        filtered_context = context.select { |k, _| _schema.include?(k) }
        @table.merge!(filtered_context)
      end

      def success?
        !failure?
      end

      def failure?
        @failure || false
      end

      def fail!(context = {})
        @table.merge!(context)
        @failure = true
        raise Interactor::Failure, self
      end

      def called!(interactor)
        _called << interactor
      end

      def rollback!
        return false if @rolled_back
        _called.reverse_each(&:rollback)
        @rolled_back = true
      end

      def _called
        @called ||= []
      end

      def _schema
        @schema
      end

      def to_h
        @table
      end

      private

      attr_reader :table

      def define_schema_methods(schema)
        singleton_class.class_exec(schema) do |names|
          names.each do |name|
            define_method(name) do
              @table[name]
            end

            define_method("#{name}=") do |value|
              @table[name] = value
            end
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
interactor-schema-0.2.1 lib/interactor/schema/context.rb
interactor-schema-0.2.0 lib/interactor/schema/context.rb