class ApiBlocks::Interactor

Attributes

input_schema[RW]

Public Class Methods

call(*args) click to toggle source

Call the interactor with its arguments.

@example

InviteUser.call(
  email: "foo@example.com",
  first_name: "Foo",
  last_name: "Bar"
)
# File lib/api_blocks/interactor.rb, line 76
def self.call(*args)
  new.call(*args)
end
input(&block) click to toggle source

Define a contract for the input of this interactor using `dry-validation`

@example

class FooInteractor < ApiBlocks::Interactor
  input do
    schema do
      required(:bar).filled
    end
  end

  step :validate_input!
end
# File lib/api_blocks/interactor.rb, line 62
def self.input(&block)
  @input_schema = Class.new(Dry::Validation::Contract, &block).new
end
with_step_args(*args) click to toggle source

Call the interactor with additional step arguments.

@example

InviteUser.with_step_args(deliver_invitation: [mailer: UserMailer])
# File lib/api_blocks/interactor.rb, line 86
def self.with_step_args(*args)
  new.with_step_args(*args)
end

Protected Instance Methods

database_transaction!(input) { |Success(input)| ... } click to toggle source

Wraps the steps inside an AR transaction.

Add this step to your interactor if you want to wrap its operations inside a database transaction

# File lib/api_blocks/interactor.rb, line 114
def database_transaction!(input)
  result = nil

  ActiveRecord::Base.transaction do
    result = yield(Success(input))
    raise ActiveRecord::Rollback if result.failure?
  end

  result
end
validate_input!(input) click to toggle source

Validates input with the class attribute `schema` if it is defined.

Add this step to your interactor if you want to validate its input.

# File lib/api_blocks/interactor.rb, line 97
def validate_input!(input)
  return Success(input) unless self.class.input_schema

  result = self.class.input_schema.call(input)

  if result.success?
    Success(result.values)
  else
    Failure(result)
  end
end