Class: SoberSwag::OutputObject::Field

Inherits:
Object
  • Object
show all
Defined in:
lib/sober_swag/output_object/field.rb

Overview

A single field in an output object. Later used to make an actual serializer from this.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, serializer, from: nil, &block) ⇒ Field

Returns a new instance of Field.

Parameters:

  • name (Symbol)

    the name of this field

  • serializer (SoberSwag::Serializer::Base, Proc, Lambda)

    how to serialize the value in this field. If given a Proc or Lambda, the Proc or Lambda should return an instance of SoberSwag::Serializer::Base when called.

  • from (Symbol) (defaults to: nil)

    an optional parameter specifying that this field should be plucked "from" another attribute of a ruby object

  • block (Proc)

    a proc to get this field from a serialized object. If not given, will try to grab an attribute with the same name, or with the name of from: if that was sent.



19
20
21
22
23
24
# File 'lib/sober_swag/output_object/field.rb', line 19

def initialize(name, serializer, from: nil, &block)
  @name = name
  @root_serializer = serializer
  @from = from
  @block = block
end

Instance Attribute Details

#nameSymbol (readonly)

Returns name of this field.

Returns:

  • (Symbol)

    name of this field.



28
29
30
# File 'lib/sober_swag/output_object/field.rb', line 28

def name
  @name
end

Instance Method Details

#resolved_serializerSoberSwag::Serializer::Base



38
39
40
41
42
43
44
# File 'lib/sober_swag/output_object/field.rb', line 38

def resolved_serializer
  if @root_serializer.is_a?(Proc)
    @root_serializer.call
  else
    @root_serializer
  end
end

#serializerSoberSwag::Serializer::Base



32
33
34
# File 'lib/sober_swag/output_object/field.rb', line 32

def serializer
  @serializer ||= resolved_serializer.serializer.via_map(&transform_proc)
end

#transform_procProc (private)

Returns:

  • (Proc)


50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/sober_swag/output_object/field.rb', line 50

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

  return @transform_proc = @block if @block

  key = @from || @name
  @transform_proc = proc do |object, _|
    if object.respond_to?(key)
      object.public_send(key)
    else
      object[key]
    end
  end
end