class SoberSwag::Serializer::FieldList

Extracts a JSON hash from a list of {SoberSwag::OutputObject::Field} structs.

Attributes

field_list[R]

@return [Array<SoberSwag::OutputObject::Field>] the list of fields to use.

Public Class Methods

new(field_list) click to toggle source

Create a new field-list serializer.

@param field_list [Array<SoberSwag::OutputObject::Field>] descriptions of each field

# File lib/sober_swag/serializer/field_list.rb, line 10
def initialize(field_list)
  @field_list = field_list
end

Public Instance Methods

finalize_lazy_type!() click to toggle source
# File lib/sober_swag/serializer/field_list.rb, line 55
def finalize_lazy_type!
  make_struct_type!
end
lazy_type() click to toggle source
# File lib/sober_swag/serializer/field_list.rb, line 51
def lazy_type
  struct_class
end
lazy_type?() click to toggle source

These types are always constructed lazily.

# File lib/sober_swag/serializer/field_list.rb, line 47
def lazy_type?
  true
end
primitive(symbol) click to toggle source

Alias to make writing primitive stuff much easier

# File lib/sober_swag/serializer/field_list.rb, line 20
def primitive(symbol)
  SoberSwag::Serializer.Primitive(SoberSwag::Types.const_get(symbol))
end
serialize(object, options = {}) click to toggle source

Serialize an object to a JSON hash by using each field in the list. @param object [Object] object to serialize @param options [Hash] arbitrary options @return [Hash] serialized object.

# File lib/sober_swag/serializer/field_list.rb, line 29
def serialize(object, options = {})
  {}.tap do |hash|
    field_list.each do |field|
      hash[field.name] = field.serializer.serialize(object, options)
    end
  end
end
type() click to toggle source

Construct a Dry::Struct from the fields given. This Struct will be swagger-able. @return [Dry::Struct]

# File lib/sober_swag/serializer/field_list.rb, line 41
def type
  @type ||= make_struct_type!
end

Private Instance Methods

make_struct_type!() click to toggle source
# File lib/sober_swag/serializer/field_list.rb, line 61
def make_struct_type! # rubocop:disable Metrics/MethodLength
  # mutual recursion makes this really, really annoying.
  return struct_class if @made_struct_type

  f = field_list
  s = identifier
  struct_class.instance_eval do
    identifier(s)
    f.each do |field|
      attribute field.name, field.serializer.lazy_type
    end
  end
  @made_struct_type = true

  field_list.map(&:serializer).each(&:finalize_lazy_type!)

  struct_class
end
struct_class() click to toggle source
# File lib/sober_swag/serializer/field_list.rb, line 80
def struct_class
  @struct_class ||= Class.new(SoberSwag::InputObject)
end