Module: RubyDoozer::Json::Deserializer
- Defined in:
- lib/ruby_doozer/json/deserializer.rb
Overview
Deserialize from JSON entries in Doozer
Class Method Summary collapse
- .deserialize(value) ⇒ Object
-
.symbolize(v) ⇒ Object
Returns the supplied value symbolized.
-
.symbolize_array(a) ⇒ Object
Returns a new Array with any symbols strings returned as symbols.
-
.symbolize_hash(hash) ⇒ Object
Returns a new hash updated with keys and values that are strings starting with ‘:’ are turned into symbols.
-
.symbolize_string(s) ⇒ Object
Returns a new string with the string parsed and symbol string converted to a symbol.
Class Method Details
.deserialize(value) ⇒ Object
8 9 10 11 12 13 14 15 16 |
# File 'lib/ruby_doozer/json/deserializer.rb', line 8 def self.deserialize(value) return nil unless value if value.strip.start_with?('{') || value.strip.start_with?('[{') symbolize(MultiJson.load(value)) else symbolize_string(value) end end |
.symbolize(v) ⇒ Object
Returns the supplied value symbolized
19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/ruby_doozer/json/deserializer.rb', line 19 def self.symbolize(v) if v.is_a?(Hash) symbolize_hash(v) elsif v.is_a?(Array) symbolize_array(v) elsif v.is_a?(String) symbolize_string(v) else v end end |
.symbolize_array(a) ⇒ Object
Returns a new Array with any symbols strings returned as symbols
46 47 48 |
# File 'lib/ruby_doozer/json/deserializer.rb', line 46 def self.symbolize_array(a) a.collect {|v| symbolize(v)} end |
.symbolize_hash(hash) ⇒ Object
Returns a new hash updated with keys and values that are strings starting with ‘:’ are turned into symbols
33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/ruby_doozer/json/deserializer.rb', line 33 def self.symbolize_hash(hash) h = hash.dup hash.each_pair do |k, v| # Convert values in the hash h[k] = symbolize(v) # Convert key to a symbol if it is a symbol string h[k[1..-1].to_sym] = h.delete(k) if k.is_a?(String) && k.start_with?(':') end h end |
.symbolize_string(s) ⇒ Object
Returns a new string with the string parsed and symbol string converted to a symbol
51 52 53 54 55 56 57 58 |
# File 'lib/ruby_doozer/json/deserializer.rb', line 51 def self.symbolize_string(s) # JSON Parser cannot parse non-hash/array values value = YAML.load(s) # Now check for symbols which are strings starting with ':' value.is_a?(String) && value.start_with?(':') ? value[1..-1].to_sym : value rescue Exception s end |