Module: Dry::Transaction::Extra::Steps::Use::DSL

Defined in:
lib/dry/transaction/extra/steps/use.rb

Instance Method Summary collapse

Instance Method Details

#use(txn_or_container, key = nil, as: nil) ⇒ Object

Invokes another transaction, or anything else #callable. Result is merged, according to the same rules as the merge step.

Alternatively accepts a Contaner, and a key registered within that container. This allows you to declare the transaction to be used at runtime, instead of file load time.

Note that this is basically equivalent to injecting the step into the initializer, or passing in a container. However, using this method may result in more readable code, and less surprise. See README for a more detailed discussion.

use FindUser.new use FindUser # When using :class_callable extension

use UserContainer, :find

use FindUser, as: “user”

# => { user: #<User: id=1> }

Examples:

Find transaction in Container

Merging output using specified key

Parameters:

  • txn_or_container (#call, Dry::Container)

    A callable, or a Container

  • key (Symbol) (defaults to: nil)

    If provided a Container, use this key for lookup

  • as (Hash) (defaults to: nil)

    a customizable set of options

Options Hash (as:):

  • When (Symbol)

    merging the output, use this as the key



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/dry/transaction/extra/steps/use.rb', line 41

def use(txn_or_container, key = nil, as: nil)
  if key
    container = txn_or_container
    method_name = as || "#{container.name}.#{key}".to_sym
  else
    txn = txn_or_container
    method_name = as || txn.name.to_sym
  end

  merge(method_name, as:)
  define_method method_name do |*args|
    txn = container[key] if key
    txn.call(*args)
  end
rescue NoMethodError => e
  raise e unless e.name == :name

  raise ArgumentError, "unable to determine step name from #{key_or_container}.\
      Pass an explicit step name using `as:` keyword argument."
end