Class: SoberSwag::Serializer::Hash

Inherits:
Base
  • Object
show all
Defined in:
lib/sober_swag/serializer/hash.rb

Overview

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#array, #identifier, #meta, #optional, #serializer, #via_map

Constructor Details

#initialize(choices, default, key_proc) ⇒ Hash

Returns a new instance of Hash.

Parameters:

  • choices (Hash<Object => SoberSwag::Serializer::Base>)

    hash of serializers that we might use.

  • default (SoberSwag::Serializer::Base)

    default to use if key not found.

  • 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.



16
17
18
19
20
# File 'lib/sober_swag/serializer/hash.rb', line 16

def initialize(choices, default, key_proc)
  @choices = choices
  @default = default
  @key_proc = key_proc
end

Instance Attribute Details

#choicesObject (readonly)

Returns the value of attribute choices.



22
23
24
# File 'lib/sober_swag/serializer/hash.rb', line 22

def choices
  @choices
end

#defaultObject (readonly)

Returns the value of attribute default.



22
23
24
# File 'lib/sober_swag/serializer/hash.rb', line 22

def default
  @default
end

#key_procObject (readonly)

Returns the value of attribute key_proc.



22
23
24
# File 'lib/sober_swag/serializer/hash.rb', line 22

def key_proc
  @key_proc
end

Instance Method Details

#finalize_lazy_type!Object



40
41
42
# File 'lib/sober_swag/serializer/hash.rb', line 40

def finalize_lazy_type!
  possible_serializers.each(&:finalize_lazy_type!)
end

#lazy_typeObject



44
45
46
# File 'lib/sober_swag/serializer/hash.rb', line 44

def lazy_type
  @lazy_type ||= possible_serializers.map(&:lazy_type).reduce(:|)
end

#lazy_type?Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/sober_swag/serializer/hash.rb', line 36

def lazy_type?
  possible_serializers.any?(&:lazy_type?)
end

#possible_serializersSet<SoberSwag::Serializer::Base>

Returns:



32
33
34
# File 'lib/sober_swag/serializer/hash.rb', line 32

def possible_serializers
  @possible_serializers ||= (choices.values + [default]).to_set
end

#serialize(object, options = {}) ⇒ Object



24
25
26
27
28
# 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

#typeObject



48
49
50
# File 'lib/sober_swag/serializer/hash.rb', line 48

def type
  @type ||= possible_serializers.map(&:type).reduce(:|)
end