Class: IknowParams::Serializer::ArrayOf
- Inherits:
-
IknowParams::Serializer
- Object
- IknowParams::Serializer
- IknowParams::Serializer::ArrayOf
- Defined in:
- lib/iknow_params/serializer/array_of.rb
Overview
Serialize an array of application types to JSON types. Does not support fully rendering to/from a JSON string.
Instance Attribute Summary collapse
-
#allow_singleton ⇒ Object
readonly
Returns the value of attribute allow_singleton.
-
#serializer ⇒ Object
readonly
Returns the value of attribute serializer.
Attributes inherited from IknowParams::Serializer
Instance Method Summary collapse
- #dump(vals, json: true) ⇒ Object
-
#initialize(serializer, allow_singleton: false) ⇒ ArrayOf
constructor
A new instance of ArrayOf.
- #load(jvals) ⇒ Object
- #matches_type?(vals) ⇒ Boolean
Methods inherited from IknowParams::Serializer
for, for!, json_value?, #matches_type!, singleton
Constructor Details
#initialize(serializer, allow_singleton: false) ⇒ ArrayOf
Returns a new instance of ArrayOf.
9 10 11 12 13 |
# File 'lib/iknow_params/serializer/array_of.rb', line 9 def initialize(serializer, allow_singleton: false) super(::Array) @serializer = serializer @allow_singleton = allow_singleton end |
Instance Attribute Details
#allow_singleton ⇒ Object (readonly)
Returns the value of attribute allow_singleton.
6 7 8 |
# File 'lib/iknow_params/serializer/array_of.rb', line 6 def allow_singleton @allow_singleton end |
#serializer ⇒ Object (readonly)
Returns the value of attribute serializer.
6 7 8 |
# File 'lib/iknow_params/serializer/array_of.rb', line 6 def serializer @serializer end |
Instance Method Details
#dump(vals, json: true) ⇒ Object
34 35 36 37 |
# File 'lib/iknow_params/serializer/array_of.rb', line 34 def dump(vals, json: true) matches_type!(vals) vals.map { |val| serializer.dump(val, json: json) } end |
#load(jvals) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/iknow_params/serializer/array_of.rb', line 15 def load(jvals) if allow_singleton jvals = Array.wrap(jvals) else unless jvals.is_a?(Array) raise IknowParams::Serializer::LoadError.new( "Incorrect type for ArrayOf: #{jvals.inspect}:#{jvals.class.name} is not an array") end end # Special case thanks to Rails' array query param format not differentating # empty arrays (i.e. `route?param[]=`). Since we can only express one of # empty array and singleton array containing empty string, we pick the more # useful former. return [] if jvals == [''] jvals.map { |jval| serializer.load(jval) } end |
#matches_type?(vals) ⇒ Boolean
39 40 41 |
# File 'lib/iknow_params/serializer/array_of.rb', line 39 def matches_type?(vals) super(vals) && vals.all? { |val| serializer.matches_type?(val) } end |