Module: Transfluent::ApiHelper
- Included in:
- Api
- Defined in:
- lib/transfluent/api_helper.rb
Instance Method Summary collapse
- #api_uri(method) ⇒ Object
- #execute_get(uri, query = nil) ⇒ Object
- #execute_post(uri, data) ⇒ Object
- #parse_response(response) ⇒ Object
- #symbolize_array(array) ⇒ Object
-
#symbolize_hash(hash) ⇒ Object
Convert string keys in a hash to symbols recursively.
Instance Method Details
#api_uri(method) ⇒ Object
6 7 8 9 10 |
# File 'lib/transfluent/api_helper.rb', line 6 def api_uri method method = '/' + method unless method[0] == '/' url = @_ROOT_URL || 'https://transfluent.com/v2' URI(url + method) end |
#execute_get(uri, query = nil) ⇒ Object
12 13 14 15 16 17 18 |
# File 'lib/transfluent/api_helper.rb', line 12 def execute_get uri, query = nil unless query.nil? uri.query = URI.encode_www_form query end parse_response(Net::HTTP.get(uri)) end |
#execute_post(uri, data) ⇒ Object
20 21 22 |
# File 'lib/transfluent/api_helper.rb', line 20 def execute_post uri, data parse_response(Net::HTTP.post_form(uri, data).body) end |
#parse_response(response) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/transfluent/api_helper.rb', line 24 def parse_response response if response.is_a? String then json = JSON.parse(response) else json = response end if json["status"] == "OK" response = json['response'] if response.is_a? Hash symbolize_hash response elsif response.is_a? Array symbolize_array response else response end elsif json["status"] == "ERROR" raise Transfluent::ApiError.new json['error']['type'], json['error']['message'] end end |
#symbolize_array(array) ⇒ Object
54 55 56 57 58 59 |
# File 'lib/transfluent/api_helper.rb', line 54 def symbolize_array array array.inject([]) do |memo, v| memo.push(if v.is_a? Hash then symbolize_hash v else v end) memo end end |
#symbolize_hash(hash) ⇒ Object
Convert string keys in a hash to symbols recursively
47 48 49 50 51 52 |
# File 'lib/transfluent/api_helper.rb', line 47 def symbolize_hash hash hash.inject({}) do |memo,(k,v)| memo[(k.to_sym rescue k) || k] = if v.is_a? Hash then symbolize_hash v else v end memo end end |