Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/fidius-common/json_symbol_addon.rb

Overview

Part of the JSON Symbol Addon.

Instance Method Summary collapse

Instance Method Details

#as_json(options = nil) ⇒ String

JSON-encodes self.

Parameters:

  • options (Hash) (defaults to: nil)

    An options-hash. Keys maybe :only, :exept or :encoder.

Returns:

  • (String)

    The JSON-encoded string of self.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/fidius-common/json_symbol_addon.rb', line 27

def as_json(options = nil)
  # create a subset of the hash by applying :only or :except
  subset = if options
    if attrs = options[:only]
      slice(*Array.wrap(attrs))
    elsif attrs = options[:except]
      except(*Array.wrap(attrs))
    else
      self
    end
  else
    self
  end

  # use encoder as a proxy to call as_json on all values in the subset, to protect from circular references
  encoder = options && options[:encoder] || ActiveSupport::JSON::Encoding::Encoder.new(options)
  
  # FIDIUS changed here to from k.to_s to k.as_json to decode strings with : as symbols
  pairs = subset.map do |k, v|
    [k.as_json, encoder.as_json(v)]
  end
  result = if self.is_a?(ActiveSupport::OrderedHash)
    ActiveSupport::OrderedHash.new
  else
    Hash.new
  end
  pairs.inject(result) do |hash, pair|
    hash[pair.first] = pair.last; hash
  end
end

#symbolize_keys_if_neededHash

Converts each key to a symbol, if the key is a String and its first character is a :.

Returns:

  • (Hash)

    The converted hash.



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/fidius-common/json_symbol_addon.rb', line 62

def symbolize_keys_if_needed
  to_add = Hash.new
  self.each_pair do |k,v|
    if v.respond_to?("symbolize_keys_if_needed")
      v.symbolize_keys_if_needed
    end
    if k[0] == ":"
      self.delete(k)
      to_add[k[1..-1].to_sym] = v
    end
  end
  to_add.each_pair do |k,v|
    self[k] = v
  end
end