Class: IknowParams::Serializer::HashOf
- Inherits:
-
IknowParams::Serializer
- Object
- IknowParams::Serializer
- IknowParams::Serializer::HashOf
- Defined in:
- lib/iknow_params/serializer/hash_of.rb
Overview
Serialize a hash structure of application types to JSON types. Does not support fully rendering to/from a JSON string.
Instance Attribute Summary collapse
-
#key_serializer ⇒ Object
readonly
Returns the value of attribute key_serializer.
-
#value_serializer ⇒ Object
readonly
Returns the value of attribute value_serializer.
Attributes inherited from IknowParams::Serializer
Instance Method Summary collapse
- #dump(structure, json: true) ⇒ Object
-
#initialize(key_serializer, value_serializer) ⇒ HashOf
constructor
A new instance of HashOf.
- #load(jstructure) ⇒ Object
- #matches_type?(vals) ⇒ Boolean
Methods inherited from IknowParams::Serializer
for, for!, json_value?, #matches_type!, singleton
Constructor Details
#initialize(key_serializer, value_serializer) ⇒ HashOf
Returns a new instance of HashOf.
9 10 11 12 13 |
# File 'lib/iknow_params/serializer/hash_of.rb', line 9 def initialize(key_serializer, value_serializer) super(::Hash) @key_serializer = key_serializer @value_serializer = value_serializer end |
Instance Attribute Details
#key_serializer ⇒ Object (readonly)
Returns the value of attribute key_serializer.
6 7 8 |
# File 'lib/iknow_params/serializer/hash_of.rb', line 6 def key_serializer @key_serializer end |
#value_serializer ⇒ Object (readonly)
Returns the value of attribute value_serializer.
6 7 8 |
# File 'lib/iknow_params/serializer/hash_of.rb', line 6 def value_serializer @value_serializer end |
Instance Method Details
#dump(structure, json: true) ⇒ Object
30 31 32 33 34 35 36 37 |
# File 'lib/iknow_params/serializer/hash_of.rb', line 30 def dump(structure, json: true) matches_type!(structure) structure.each_with_object({}) do |(key, value), result| jkey = key_serializer.dump(key, json: false) jvalue = value_serializer.dump(value, json: json) result[jkey] = jvalue end end |
#load(jstructure) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/iknow_params/serializer/hash_of.rb', line 15 def load(jstructure) jstructure = jstructure.to_unsafe_h if jstructure.is_a?(ActionController::Parameters) unless jstructure.is_a?(Hash) raise IknowParams::Serializer::LoadError.new( "Incorrect type for HashOf: #{jstructure.inspect}:#{jstructure.class.name} is not a hash") end jstructure.each_with_object({}) do |(jkey, jvalue), result| key = key_serializer.load(jkey) value = value_serializer.load(jvalue) result[key] = value end end |
#matches_type?(vals) ⇒ Boolean
39 40 41 42 43 |
# File 'lib/iknow_params/serializer/hash_of.rb', line 39 def matches_type?(vals) super(vals) && vals.all? do |k_val, v_val| key_serializer.matches_type?(k_val) && value_serializer.matches_type?(v_val) end end |