Class: JSONHash
- Inherits:
-
Object
- Object
- JSONHash
- 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
-
.parse(from) ⇒ Array, JSONHash
Build an array of JSONHash objects if the argument is an array of Hash instances.
Instance Method Summary collapse
-
#initialize(json) ⇒ JSONHash
constructor
Initializer.
-
#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.
-
#to_json ⇒ JSON
Returns the underling JSON parsed hash structure.
-
#to_s ⇒ String
Return a string representation of the JSON parsed hash structure.
Constructor Details
#initialize(json) ⇒ JSONHash
Initializer. The json parameter is a Ruby hash. Usually you would call JSON.parse to get such a hash.
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.
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.
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_json ⇒ JSON
Returns the underling JSON parsed hash structure.
41 42 43 |
# File 'lib/json_hash.rb', line 41 def to_json @json end |
#to_s ⇒ String
Return a string representation of the JSON parsed hash structure.
49 50 51 |
# File 'lib/json_hash.rb', line 49 def to_s @json.to_s end |