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.
Constant Summary collapse
- VERSION =
"1.0.0"
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.
18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/json_hash.rb', line 18 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.
35 36 37 |
# File 'lib/json_hash.rb', line 35 def method_missing(method, *args) @json[method.to_s] || @json[method.to_sym] || 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.
63 64 65 66 67 68 69 70 |
# File 'lib/json_hash.rb', line 63 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.
43 44 45 |
# File 'lib/json_hash.rb', line 43 def to_json @json end |
#to_s ⇒ String
Return a string representation of the JSON parsed hash structure.
51 52 53 |
# File 'lib/json_hash.rb', line 51 def to_s @json.to_s end |