Module: Dry::Tuple::Struct::ClassInterface

Includes:
ClassDecorator
Included in:
Dry::Tuple::Struct
Defined in:
lib/dry/tuple/struct.rb

Overview

Extracted due to make it possible to use this feature within Struct classes.

Examples:

extending Dry::Struct subclass


class SomeStruct < Dry::Struct
  attribute :some, Types::Integer
  attribute :with, Types::Hash

  extend ::Dry::Tuple::Struct::ClassInterface
  auto_tuple :some, :with
end

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ClassDecorator

#call_safe, #call_unsafe, #new_from_tuple

Class Method Details

.extended(base) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



64
65
66
67
68
69
# File 'lib/dry/tuple/struct.rb', line 64

def self.extended(base)
  base.defines :tuple, coerce: TypeCoercer
  base.defines :keys_order, type: Dry::Types['array<symbol>']
  base.keys_order EMPTY_ARRAY
  super
end

Instance Method Details

#auto_tuple(*keys) ⇒ void

This method returns an undefined value.

Merges the given keys into the #keys_order and redefines the tuple of class.

Parameters:

  • keys (Array<Symbol>)


41
42
43
44
45
# File 'lib/dry/tuple/struct.rb', line 41

def auto_tuple(*keys)
  keys_order(keys_order | keys)
  index = schema.keys.map { |t| [t.name, t.type] }.to_h
  tuple Dry::Types::Tuple.coerce(index.values_at(*keys_order))
end

#coerce_tuple(input) ⇒ Hash

Constructs a hash of struct attributes from the given array by zipping within #keys_order.

Parameters:

  • input (Array<Any>)

Returns:

  • (Hash)


50
51
52
# File 'lib/dry/tuple/struct.rb', line 50

def coerce_tuple(input)
  keys_order.zip(input).to_h
end

#try(input, &block) ⇒ Dry::Types::Result

Returns:

  • (Dry::Types::Result)


55
56
57
58
59
60
61
# File 'lib/dry/tuple/struct.rb', line 55

def try(input, &block)
  if input.is_a?(::Array)
    tuple.try(input, &block)
  else
    super(input, &block)
  end
end