Class: Spout::Helpers::JsonRequest
- Inherits:
-
Object
- Object
- Spout::Helpers::JsonRequest
- Defined in:
- lib/spout/helpers/json_request.rb
Overview
Generates JSON web requests for GET.
Instance Attribute Summary collapse
-
#url ⇒ Object
readonly
Returns the value of attribute url.
Class Method Summary collapse
Instance Method Summary collapse
- #get ⇒ Object
-
#initialize(url, args = {}) ⇒ JsonRequest
constructor
A new instance of JsonRequest.
- #key_value_to_string(key, value, scope = nil) ⇒ Object
- #nested_hash_to_params(args) ⇒ Object
Constructor Details
#initialize(url, args = {}) ⇒ JsonRequest
Returns a new instance of JsonRequest.
20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/spout/helpers/json_request.rb', line 20 def initialize(url, args = {}) @params = nested_hash_to_params(args) @url = URI.parse(url) @http = Net::HTTP.new(@url.host, @url.port) if @url.scheme == "https" @http.use_ssl = true @http.verify_mode = OpenSSL::SSL::VERIFY_NONE end rescue @error = "Invalid URL: #{url.inspect}" puts @error.red end |
Instance Attribute Details
#url ⇒ Object (readonly)
Returns the value of attribute url.
18 19 20 |
# File 'lib/spout/helpers/json_request.rb', line 18 def url @url end |
Class Method Details
.get(url, *args) ⇒ Object
13 14 15 |
# File 'lib/spout/helpers/json_request.rb', line 13 def get(url, *args) new(url, *args).get end |
Instance Method Details
#get ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/spout/helpers/json_request.rb', line 34 def get return unless @error.nil? full_path = @url.path query = ([@url.query] + @params).flatten.compact.join("&") full_path += "?#{query}" if query.to_s != "" response = @http.start do |http| http.get(full_path) end [JSON.parse(response.body), response] rescue => e puts "GET Error: #{e}".red end |
#key_value_to_string(key, value, scope = nil) ⇒ Object
54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/spout/helpers/json_request.rb', line 54 def key_value_to_string(key, value, scope = nil) current_scope = (scope ? "#{scope}[#{key}]" : key) if value.is_a? Hash value.collect do |k,v| key_value_to_string(k, v, current_scope) end.join("&") elsif value.is_a? Array value.collect do |v| key_value_to_string("", v, current_scope) end else "#{current_scope}=#{CGI.escape(value.to_s)}" end end |
#nested_hash_to_params(args) ⇒ Object
48 49 50 51 52 |
# File 'lib/spout/helpers/json_request.rb', line 48 def nested_hash_to_params(args) args.collect do |key, value| key_value_to_string(key, value, nil) end end |