module RubyDoozer::Json::Deserializer

Deserialize from JSON entries in Doozer

Public Class Methods

deserialize(value) click to toggle source
# File lib/ruby_doozer/json/deserializer.rb, line 8
def self.deserialize(value)
  return value if value.nil? || (value == '')

  if value.strip.start_with?('{') || value.strip.start_with?('[{')
    symbolize(MultiJson.load(value))
  else
    symbolize_string(value)
  end
end
symbolize(v) click to toggle source

Returns the supplied value symbolized

# 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) click to toggle source

Returns a new Array with any symbols strings returned as symbols

# File lib/ruby_doozer/json/deserializer.rb, line 46
def self.symbolize_array(a)
  a.collect {|v| symbolize(v)}
end
symbolize_hash(hash) click to toggle source

Returns a new hash updated with keys and values that are strings starting with ':' are turned into symbols

# 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) click to toggle source

Returns a new string with the string parsed and symbol string converted to a symbol

# 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