Class: ApiSerializer::TypedStruct

Inherits:
Literal::Struct
  • Object
show all
Includes:
Literal::Types
Defined in:
lib/api_serializer/typed_struct.rb

Direct Known Subclasses

TargetDataStructure

Defined Under Namespace

Classes: AttributeReflection

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.attribute(name, type, reader: :public, positional: false, default: nil, &coercion) ⇒ Object



10
11
12
13
14
15
16
# File 'lib/api_serializer/typed_struct.rb', line 10

def attribute(name, type, reader: :public, positional: false, default: nil, &coercion)
  attribute_options[name] = AttributeReflection.new(
    name:, type:, reader:, positional:, default:, coercion:
  )
  prop(name, type, positional ? :positional : :keyword,
    reader: reader || :public, writer: false, default:, &coercion)
end

.attribute_namesObject



19
# File 'lib/api_serializer/typed_struct.rb', line 19

def attribute_names = attribute_options.keys

.attribute_optionsObject



21
22
23
24
25
26
27
28
29
# File 'lib/api_serializer/typed_struct.rb', line 21

def attribute_options
  return @attribute_options if defined?(@attribute_options)

  @attribute_options = if superclass < TypedStruct
    superclass.attribute_options.dup
  else
    {}
  end
end

.reflect_on(name) ⇒ Object



18
# File 'lib/api_serializer/typed_struct.rb', line 18

def reflect_on(name) = attribute_options[name]

Instance Method Details

#attributesObject



43
# File 'lib/api_serializer/typed_struct.rb', line 43

def attributes = to_h

#inspectObject



32
33
34
# File 'lib/api_serializer/typed_struct.rb', line 32

def inspect
  "#<#{self.class.name} #{attributes.map { "#{_1}: #{_2.inspect}" }.join(", ")}>"
end

#merge(other, ignore_nils: false) ⇒ Object

Raises:

  • (ArgumentError)


36
37
38
39
40
41
# File 'lib/api_serializer/typed_struct.rb', line 36

def merge(other, ignore_nils: false)
  raise ArgumentError, "merge requires an instance of the same TypedStruct class" unless other.instance_of?(self.class)

  other_attributes = ignore_nils ? other.attributes.reject { _2.nil? } : other.attributes
  self.class.new(**attributes.merge(other_attributes))
end