collectiveidea / interactor

Interactor provides a common interface for performing complex user interactions.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Default values for parameters

NoMemoryError opened this issue · comments

How can I get params with default values within the interactor. For example

class PayParkingTransaction
  include Interactor
  delegate parking_transaction, to: :context

  def call
    puts parking_transaction
  end
end
t = 'test'
PayParkingTransaction.call(parking_transaction: t) 

This will output test

t = nil
PayParkingTransaction.call(parking_transaction: t) 

This will output nil but I would like to have is a default in this case that when t is nil, it will take a default value. Ofcourse I can set it manually in the interactor but I don't want to do that for all interactors I have. Is there any other better way to achieve this?

If it were me, I'd use a before block in my interactor:

before do
  context.parking_transaction ||= my_default_value
end

If the logic is similar across multiple interactors, you could pull that logic out into a concern that's included in those interactors:

class MyInteractor
  include Interactor
  include TransactionDefaults

  def call
    # …
  end
end

module TransactionDefaults
  extend ActiveSupport::Concern

  included do
    before do
      context.parking_transaction = my_default_value
    end
  end
end

The other thing to do would be to apply your defaults before you pass them into the interactor.

Unfortunately, Interactor just cannot know your intentions. Passing nil into an interactor's context is a perfectly legitimate use case so we don't do any clever protection against that sort of thing.

I hope that helps!

@laserlemon Thanks a lot. Didn't realize that before block was available here. This seems like a perfect solution.