Sha256: 0d8166b81b1b72684cabd7f67ed66ca9483593d7a226a2b5d8418e7f181acf1e

Contents?: true

Size: 1.53 KB

Versions: 9

Compression:

Stored size: 1.53 KB

Contents

# frozen_string_literal: true

require_relative '../operation'
require_relative 'resource'

module LedgerSync
  module Domains
    class Operation
      class Transition < Resource
        class Contract < LedgerSync::Ledgers::Contract
          params do
            required(:model_name).filled(:string)
            required(:id).filled(:integer)
            required(:event).value(:string)
            required(:attrs).maybe(:hash)
            required(:attrs).maybe(:array)
            required(:limit).value(:hash)
          end
        end

        private

        def operate
          if resource.present?
            if resource.send(guard_method, params[:attrs]) &&
               resource.send(event_method, params[:attrs])
              success
            else
              failure('Unable to transition')
            end
          else
            failure('Not found')
          end
        end

        def guard_method
          "may_#{params[:event]}?"
        end

        def event_method
          "#{params[:event]}!"
        end

        def resource
          @resource ||= resource_class.where(params[:limit]).find_by(id: params[:id])
        end

        def resource_class
          @resource_class ||= Object.const_get(params[:model_name])
        end

        def success
          super(resource)
        end

        def failure(message)
          super(
            LedgerSync::Error::OperationError.new(
              operation: self,
              message: message
            )
          )
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
ledger_sync-domains-1.2.1 lib/ledger_sync/domains/operation/transition.rb
ledger_sync-domains-1.2.0 lib/ledger_sync/domains/operation/transition.rb
ledger_sync-domains-1.1.4 lib/ledger_sync/domains/operation/transition.rb
ledger_sync-domains-1.1.3 lib/ledger_sync/domains/operation/transition.rb
ledger_sync-domains-1.1.1 lib/ledger_sync/domains/operation/transition.rb
ledger_sync-domains-1.1.0 lib/ledger_sync/domains/operation/transition.rb
ledger_sync-domains-1.0.5 lib/ledger_sync/domains/operation/transition.rb
ledger_sync-domains-1.0.4 lib/ledger_sync/domains/operation/transition.rb
ledger_sync-domains-1.0.3 lib/ledger_sync/domains/operation/transition.rb