Class: CTG::Response::JSONResponse
- Inherits:
-
CTG::Response
- Object
- CTG::Response
- CTG::Response::JSONResponse
- Defined in:
- lib/ctg/response/json_response.rb
Instance Attribute Summary collapse
-
#data ⇒ Object
readonly
Returns the value of attribute data.
Attributes inherited from CTG::Response
Instance Method Summary collapse
-
#find(key, data = @data) ⇒ Object
Recursively find the first occurrence of a key in the JSON data.
- #find_all(key) ⇒ Object
-
#initialize(response_body, client) ⇒ JSONResponse
constructor
Initializes the JSONResponse object by parsing the JSON data.
-
#query(*keys) ⇒ Object
Queries the JSON data by keys.
Methods inherited from CTG::Response
Constructor Details
#initialize(response_body, client) ⇒ JSONResponse
Initializes the JSONResponse object by parsing the JSON data
24 25 26 27 |
# File 'lib/ctg/response/json_response.rb', line 24 def initialize(response_body, client) super(client) @data = JSON.parse(response_body) end |
Instance Attribute Details
#data ⇒ Object (readonly)
Returns the value of attribute data.
19 20 21 |
# File 'lib/ctg/response/json_response.rb', line 19 def data @data end |
Instance Method Details
#find(key, data = @data) ⇒ Object
Recursively find the first occurrence of a key in the JSON data
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/ctg/response/json_response.rb', line 55 def find(key, data = @data) case data when Hash return data[key] if data.key?(key) data.each_value do |value| result = find(key, value) return result if result end when Array data.each do |element| result = find(key, element) return result if result end end nil end |
#find_all(key) ⇒ Object
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/ctg/response/json_response.rb', line 73 def find_all(key) results = [] stack = [@data] until stack.empty? current_data = stack.pop case current_data when Hash results << current_data[key] if current_data.key?(key) stack.concat(current_data.values) when Array stack.concat(current_data) end end results.compact end |
#query(*keys) ⇒ Object
Queries the JSON data by keys
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/ctg/response/json_response.rb', line 32 def query(*keys) keys.reduce(@data) do |current_data, key| case current_data when Array case key when '*' # Handle wildcard for array access current_data.map { |element| element.is_a?(Hash) ? element : {} } when Integer current_data[key] else # If key is not an integer but the current data is an array, try to map over it current_data.map { |element| element[key] if element.is_a?(Hash) }.compact end when Hash current_data[key] end end end |