Class: JSONHash

Inherits:
Object
  • Object
show all
Defined in:
lib/json_hash.rb

Overview

Provides syntactic sugar to a JSON structure. Given a Ruby hash h, instead of using h to obtain its value, you can use the syntax of h.key, as if you are invoking a method.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(json) ⇒ JSONHash

Initializer. The json parameter is a Ruby hash. Usually you would call JSON.parse to get such a hash.

Parameters:

  • json (Hash)

    A Ruby hash, usually obtained by calling JSON.parse or HTTP GET on a .json endpoint.



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/json_hash.rb', line 16

def initialize(json)
  @json = json
  @json.each do |key,value|
    if value.class == Hash
      @json[key] = JSONHash.new(value)
    elsif value.class == Array
      values = value.collect { |v| v.class == Hash ? JSONHash.new(v) : v }
      @json[key] = values
    end
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object

Whatever .method is invoked, it will convert that to a string and use it as the key to look it up in the hash.

Parameters:

  • method (String, Symbol)

    The name of method to invoke.

  • args

    The arguments supplied to the method.



33
34
35
# File 'lib/json_hash.rb', line 33

def method_missing(method, *args)
  @json[method.to_s] || super
end

Class Method Details

.parse(from) ⇒ Array, JSONHash

Build an array of JSONHash objects if the argument is an array of Hash instances. If the argument is an URI, then parse the URI contents with JSON.parse, and then build it. If the argument is a string, then parse it using JSON.parse first, then try to parse it again. Otherwise, assume it’s a single Hash object and build just a single JSONHash object.

Parameters:

  • from (Array, Hash, String, URI)

    Object to build from.

Returns:

  • (Array, JSONHash)

    Either an array of JSONHash objects or a single JSONHash object.



61
62
63
64
65
66
67
68
# File 'lib/json_hash.rb', line 61

def self.parse(from)
  return JSONHash.new(from) if from.class == Hash
  return from.collect { |item| parse(item) } if from.class == Array
  return parse(JSON.parse(open(from) { |fp| fp.read })) if from.is_a? URI::Generic
  # Assume from is String from here on
  return parse(URI.parse(from)) if /^http[s]?:\/\/.+/ =~ from
  return parse(JSON.parse(from))
end

Instance Method Details

#to_jsonJSON

Returns the underling JSON parsed hash structure.

Returns:

  • (JSON)

    Underlying JSON object.



41
42
43
# File 'lib/json_hash.rb', line 41

def to_json
  @json
end

#to_sString

Return a string representation of the JSON parsed hash structure.

Returns:

  • (String)

    String representation of the underlying JSON object.



49
50
51
# File 'lib/json_hash.rb', line 49

def to_s
  @json.to_s
end