Module: Interactor::Contracts::DSL

Defined in:
lib/interactor/contracts/dsl.rb

Overview

Defines the class-level DSL that enables Interactor contracts.

Instance Method Summary collapse

Instance Method Details

#assures(&block) ⇒ void

This method returns an undefined value.

Defines the assurances of an Interactor and creates an after hook

Examples:

class CreatePerson
  include Interactor
  include Interactor::Contracts

  assures do
    required(:person).filled
  end

  def call
    context.person = Person.new
  end
end

26
27
28
29
# File 'lib/interactor/contracts/dsl.rb', line 26

def assures(&block)
  contract.add_assurance(&block)
  define_assurances_hook
end

#contractContract

The Contract to enforce on calls to the Interactor

Examples:

class CreatePerson
  include Interactor
  include Interactor::Contracts

  assures do
    required(:person).filled
  end

  contracts  #=> <#Interactor::Contracts::Contract>
end

47
48
49
# File 'lib/interactor/contracts/dsl.rb', line 47

def contract
  @contract ||= Contract.new
end

#expects(&block) ⇒ void

This method returns an undefined value.

Defines the expectations of an Interactor and creates a before hook

Examples:

class CreatePerson
  include Interactor
  include Interactor::Contracts

  expects do
    required(:name).filled
  end

  def call
    context.person = Person.create!(:name => context.name)
  end
end

CreatePerson.call(:first_name => "Billy").success?  #=> false
CreatePerson.call(:name => "Billy").success?        #=> true

73
74
75
76
# File 'lib/interactor/contracts/dsl.rb', line 73

def expects(&block)
  contract.add_expectation(&block)
  define_expectations_hook
end

#on_breach(&block) ⇒ void

This method returns an undefined value.

Defines a consequence that is called when a contract is breached

Examples:

class CreatePerson
  include Interactor
  include Interactor::Contracts

  expects do
    required(:name).filled
  end

  on_breach do |breaches|
    context.fail!(:message => "invalid_#{breaches.first.property}")
  end

  def call
    context.person = Person.create!(:name => context.name)
  end
end

CreatePerson.call(:first_name => "Billy").message  #=> "invalid_name"

103
104
105
# File 'lib/interactor/contracts/dsl.rb', line 103

def on_breach(&block)
  contract.add_consequence(block)
end