Class: Pepipost::APIHelper
- Inherits:
-
Object
- Object
- Pepipost::APIHelper
- Defined in:
- lib/pepipost/api_helper.rb
Class Method Summary collapse
-
.append_url_with_query_parameters(query_builder, parameters) ⇒ Object
Appends the given set of parameters to the given query string.
-
.append_url_with_template_parameters(query_builder, parameters) ⇒ Object
Replaces template parameters in the given url.
-
.clean_url(url) ⇒ String
Validates and processes the given Url.
Class Method Details
.append_url_with_query_parameters(query_builder, parameters) ⇒ Object
Appends the given set of parameters to the given query string
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/pepipost/api_helper.rb', line 35 def self.append_url_with_query_parameters(query_builder, parameters) # perform parameter validation raise ArgumentError, 'Given value for parameter \"query_builder\" is invalid.' unless query_builder.is_a? String # return if there are no parameters to replace abort('no parameters to append') if parameters.nil? # remove any nil values parameters = parameters.reject { |_key, value| value.nil? } # does the query string already has parameters has_params = query_builder.include? '?' separator = has_params ? '&' : '?' # append query with separator and parameters query_builder << separator << URI.unescape(URI.encode_www_form(parameters)) end |
.append_url_with_template_parameters(query_builder, parameters) ⇒ Object
Replaces template parameters in the given url
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/pepipost/api_helper.rb', line 6 def self.append_url_with_template_parameters(query_builder, parameters) # perform parameter validation raise ArgumentError, 'Given value for parameter \"query_builder\" is invalid.' unless query_builder.is_a? String # return if there are no parameters to replace abort('no parameters to append') if parameters.nil? # iterate and append parameters parameters.map do |key, value| replace_value = '' if value.nil? replace_value = '' elsif value.is_a? Enumerable replace_value = value.join('/') else replace_value = value.to_s end # find the template parameter and replace it with its value query_builder = query_builder.gsub('{' + key.to_s + '}', replace_value) end query_builder end |
.clean_url(url) ⇒ String
Validates and processes the given Url
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/pepipost/api_helper.rb', line 56 def self.clean_url(url) # perform parameter validation raise ArgumentError, 'Invalid Url.' unless url.is_a? String # ensure that the urls are absolute matches = url.match(%r{^(https?:\/\/[^\/]+)}) raise ArgumentError, 'Invalid Url format.' if matches.nil? # get the http protocol match protocol = matches[1] # remove redundant forward slashes query = url[protocol.length..-1].gsub(%r{\/\/+}, '/') # return process url protocol + query end |