Class: RShade::Serializer::Traversal
- Defined in:
- lib/rshade/serializer/traversal.rb
Instance Attribute Summary collapse
-
#types ⇒ Object
readonly
Returns the value of attribute types.
Instance Method Summary collapse
- #call(hash) ⇒ Object
- #default_types ⇒ Object
-
#initialize(custom_types = {}) ⇒ Traversal
constructor
A new instance of Traversal.
- #traverse(value) ⇒ Object
Constructor Details
#initialize(custom_types = {}) ⇒ Traversal
Returns a new instance of Traversal.
6 7 8 |
# File 'lib/rshade/serializer/traversal.rb', line 6 def initialize(custom_types={}) @types = default_types.merge(custom_types) end |
Instance Attribute Details
#types ⇒ Object (readonly)
Returns the value of attribute types.
4 5 6 |
# File 'lib/rshade/serializer/traversal.rb', line 4 def types @types end |
Instance Method Details
#call(hash) ⇒ Object
10 11 12 13 14 15 16 |
# File 'lib/rshade/serializer/traversal.rb', line 10 def call(hash) new_val = {} hash.each do |name, value| new_val[name] = traverse(value) end new_val end |
#default_types ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/rshade/serializer/traversal.rb', line 18 def default_types { default: ->(value) { value.to_s }, Integer => ->(value) { value }, Float => ->(value) { value }, Numeric => ->(value) { value }, String => ->(value) { value }, Hash => ->(value) do hash = {} value.each do |k,v| hash[k] = traverse(v) end hash end, Array => ->(value) do value.map { |item| traverse(item) } end } end |
#traverse(value) ⇒ Object
38 39 40 41 42 43 44 |
# File 'lib/rshade/serializer/traversal.rb', line 38 def traverse(value) klass = value klass = value.class unless value.is_a?(Class) serializer = types[klass] serializer = types[:default] unless serializer serializer.call(value) end |