class HttpHelper

Public Class Methods

new() click to toggle source

Constructor method for HttpHelper. Initialize local data.

# File lib/httpHelper.rb, line 14
def initialize()
  @uri = URI.parse 'https://api.thingdom.io'
  @path = '/1.1'
  @request_counter = 0;
end

Public Instance Methods

get_data( requestPath ) click to toggle source

Perform a HTTP GET request.

@param [String] requestPath Contains path and optional query parameters (e.g. path/to/somewhere?param1=1&param2=2) @return [Hash] The request response.

# File lib/httpHelper.rb, line 26
def get_data( requestPath )
  do_request( requestPath )
end
post_data( requestPath, data ) click to toggle source

Perform a HTTP Post request.

@param [String] requestPath Contains path to where data will be posted (e.g. path/to/post/endpoint) @param [Hash] data The data to be posted. @return [Hash] The request response.

# File lib/httpHelper.rb, line 37
def post_data( requestPath, data )
  @request_counter += 1
  data[:counter] = @request_counter
  data[:time] = Time.now.strftime( '%Y/%m/%d %H:%M:%S' )
  do_request( requestPath, data )
end

Private Instance Methods

do_request( requestPath, data = nil ) click to toggle source

Perform HTTP request.

@param [String] requestPath Contains path to where data will be retrieved or posted (e.g. path/to/post-or-get/endpoint) @param [Hash] data The data to be posted. @return [Hash] The request response.

# File lib/httpHelper.rb, line 68
def do_request( requestPath, data = nil )
  #
  # Initialize HTTPS.
  #
  https = Net::HTTP.new( @uri.host, @uri.port )
  https.use_ssl = true
  https.verify_mode =  OpenSSL::SSL::VERIFY_PEER
  https.ca_file = File.join( File.dirname( __FILE__ ), 'cacert.pem' )
  #
  # Build request.
  #
  if( data.nil? )
    request = Net::HTTP::Get.new( @path + '/' + requestPath )
  else
    request = Net::HTTP::Post.new( @path + '/' + requestPath )
    request.initialize_http_header( {'Content-Type' => 'application/json'} )
    request.body = data.to_json
  end
  #
  # Send request and convert JSON response into a hash.
  #
  response = https.request( request )
  jsonHash = json_to_hash( response.body )
end
json_to_hash( jsonString ) click to toggle source

Convert JSON string to a hash where all keys are Symbols.

@param [String] jsonString The JSON string. @return [Hash] A hash table representation of the JSON string.

# File lib/httpHelper.rb, line 55
def json_to_hash( jsonString )
  jsonHash = JSON.parse( jsonString )
  jsonHash = Hash[jsonHash.map{ |k, v| [k.to_sym, v] }]
  return jsonHash
end