class SoberSwag::Serializer::Hash

Serialize via hash lookup. This is used to speed up serialization of views, but it may be useful elsewhere.

Attributes

choices[R]
default[R]
key_proc[R]

Public Class Methods

new(choices, default, key_proc) click to toggle source

@param choices [Hash<Object => SoberSwag::Serializer::Base>] hash of serializers

that we might use.

@param default [SoberSwag::Serializer::Base] default to use if key not found. @param key_proc [Proc<Object, Hash>] extract the key we are interested in from the proc.

Will be called with the object to serialize and the options hash.
# File lib/sober_swag/serializer/hash.rb, line 16
def initialize(choices, default, key_proc)
  @choices = choices
  @default = default
  @key_proc = key_proc
end

Public Instance Methods

finalize_lazy_type!() click to toggle source
# File lib/sober_swag/serializer/hash.rb, line 40
def finalize_lazy_type!
  possible_serializers.each(&:finalize_lazy_type!)
end
lazy_type() click to toggle source
# File lib/sober_swag/serializer/hash.rb, line 44
def lazy_type
  @lazy_type ||= possible_serializers.map(&:lazy_type).reduce(:|)
end
lazy_type?() click to toggle source
# File lib/sober_swag/serializer/hash.rb, line 36
def lazy_type?
  possible_serializers.any?(&:lazy_type?)
end
possible_serializers() click to toggle source

@return [Set<SoberSwag::Serializer::Base>]

# File lib/sober_swag/serializer/hash.rb, line 32
def possible_serializers
  @possible_serializers ||= (choices.values + [default]).to_set
end
serialize(object, options = {}) click to toggle source
# File lib/sober_swag/serializer/hash.rb, line 24
def serialize(object, options = {})
  key = key_proc.call(object, options)

  choices.fetch(key) { default }.serialize(object, options)
end
type() click to toggle source
# File lib/sober_swag/serializer/hash.rb, line 48
def type
  @type ||= possible_serializers.map(&:type).reduce(:|)
end