Module: ServiceBase::ArgumentTypeAnnotations

Included in:
Service
Defined in:
lib/service_base/argument_type_annotations.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(klass) ⇒ Object



6
7
8
9
10
# File 'lib/service_base/argument_type_annotations.rb', line 6

def extended(klass)
  if !klass.is_a?(Class) || !klass.ancestors.include?(Dry::Struct)
    raise(TypeError, "#{name} should be extended on a Dry::Struct subclass")
  end
end

.included(klass) ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/service_base/argument_type_annotations.rb', line 12

def included(klass)
  if !klass.singleton_class? || !klass.attached_object.ancestors.include?(Dry::Struct)
    raise(TypeError, "#{name} should be included on the singleton class of a Dry::Struct subclass")
  end

  # `Types` overrides default types to help shorthand Type::String.
  # To access Ruby's native types within a service, use `::`, ie. `::String`
  klass.attached_object.include(Types)
end

Instance Method Details

#argument(name, type, configuration = {}) ⇒ Object

Defines an argument using the ServiceBase DSL. Under the hood, this uses dry-struct’s attribute DSL.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/service_base/argument_type_annotations.rb', line 25

def argument(name, type, configuration = {}, &)
  description = configuration[:description] == "" ? nil : configuration[:description]
  type = type.meta(description:)

  default = configuration[:default]
  validate_frozen_default!(name:, default:)

  optional = configuration.fetch(:optional, false)
  validate_optional_or_default!(optional:, default:, name:)

  type = set_default(type:, default:)

  if optional
    # attribute? allows the key to be omitted.
    # .optional allows the value to be nil.
    # https://dry-rb.org/gems/dry-types/1.2/optional-values/
    # https://github.com/dry-rb/dry-struct/blob/master/lib/dry/struct/class_interface.rb#L141-L169
    attribute?(name, type.optional, &)
  else
    # https://github.com/dry-rb/dry-struct/blob/master/lib/dry/struct/class_interface.rb#L30-L104
    attribute(name, type, &)
  end
end