Class: ServiceActor::Checks::TypeCheck

Inherits:
Base
  • Object
show all
Defined in:
lib/service_actor/checks/type_check.rb

Overview

Adds ‘type:` checking to inputs and outputs. Accepts class names or classes that should match an ancestor. Also accepts arrays.

Example:

class ReduceOrderAmount < Actor
  input :order, type: "Order"
  input :amount, type: [Integer, Float]
  input :bonus_applied, type: [TrueClass, FalseClass]
end

class ReduceOrderAmount < Actor
  input :order, type: { is: Order, message: "Order is required" }
  input :amount, type: { is: Integer, message: "Incorrect amount" }

  input :bonus_applied,
        type: {
          is: [TrueClass, FalseClass],
          message: (lambda do |origin:, input_key:, actor:, expected_type:, given_type:| # rubocop:disable Layout/LineLength
            "Wrong type \"#{given_type}\" for \"#{input_key}\". " \
            "Expected: \"#{expected_type}\""
          end)
        }
end

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(origin:, input_key:, actor:, type_definition:, given_type:) ⇒ TypeCheck

Returns a new instance of TypeCheck.



59
60
61
62
63
64
65
66
67
# File 'lib/service_actor/checks/type_check.rb', line 59

def initialize(origin:, input_key:, actor:, type_definition:, given_type:)
  super()

  @origin = origin
  @input_key = input_key
  @actor = actor
  @type_definition = type_definition
  @given_type = given_type
end

Class Method Details

.check(check_name:, origin:, input_key:, actor:, conditions:, result:) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/service_actor/checks/type_check.rb', line 38

def check(
  check_name:,
  origin:,
  input_key:,
  actor:,
  conditions:,
  result:,
  **
) # do
  return unless check_name == :type

  new(
    origin: origin,
    input_key: input_key,
    actor: actor,
    type_definition: conditions,
    given_type: result[input_key],
  ).check
end

Instance Method Details

#checkObject



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/service_actor/checks/type_check.rb', line 69

def check
  return if @type_definition.nil?
  return if @given_type.nil?

  types, message = define_types_and_message

  return if types.any? { |type| @given_type.is_a?(type) }

  add_argument_error(
    message,
    origin: @origin,
    input_key: @input_key,
    actor: @actor,
    expected_type: types.join(", "),
    given_type: @given_type.class,
  )
end