Class: Overture::Interactor

Inherits:
Object
  • Object
show all
Includes:
Interactor
Defined in:
lib/overture/interactor.rb

Overview

This is a subclass of [‘::Interactor`](github.com/collectiveidea/interactor) with some methods added for comodity.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.required(*input) ⇒ Object

Mark context keys as required.

If any of the specified keys are sent as ‘nil`, it will fail with a message like `’<key> is required’‘.

Possible options are:

  • ‘allow_empty` Allows empty values such as `[]`, `”`

Example:

class MyInteractor < Overture::Interactor

required :first_name, :last_name, allow_empty: true

end



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/overture/interactor.rb', line 27

def required(*input)
  before do
    opts = input.last.is_a?(Hash) ? input.pop : {}
    allow_empty = opts[:allow_empty]

    input.each do |attr|
      value = context.public_send(attr)
      value = value.strip if value.respond_to?(:strip)
      empty = value.respond_to?(:empty?) ? value.empty? : false
      valid = !value.nil? && (allow_empty ? true : !empty)
      fail!("#{attr} is required") unless valid
    end
  end
end

Instance Method Details

#blank?(value) ⇒ Boolean

Checks for presence and non-emptiness

Returns:

  • (Boolean)


51
52
53
54
55
56
# File 'lib/overture/interactor.rb', line 51

def blank?(value)
  return true if value.nil?

  value = value.strip if value.respond_to?(:strip)
  value.empty?
end

#context_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


69
70
71
# File 'lib/overture/interactor.rb', line 69

def context_key?(key)
  context.to_h.key?(key.to_sym)
end

#context_slice(*keys, include_nils: false) ⇒ Object

Slice the passed keys from context if they’re present.

When ‘include_nils` is false, `nil` values are ignored.



61
62
63
64
65
66
67
# File 'lib/overture/interactor.rb', line 61

def context_slice(*keys, include_nils: false)
  keys.each_with_object({}) do |key, memo|
    next unless context_key?(key)

    memo[key] = context[key] if !context[key].nil? || include_nils
  end
end

#fail!(message, meta = {}) ⇒ Object

Fails context and sets ‘context.error` attribute to the passed message.

An optional hash can be passed that will get merged when failing.



46
47
48
# File 'lib/overture/interactor.rb', line 46

def fail!(message, meta = {})
  context.fail!(meta.merge(error: message))
end