module ElectricProfile require 'net/http' require 'net/https' require 'json' class Client attr_reader :successful, :data, :error def initialize raise ArgumentError, 'Customer token is required' unless @customer_token = ENV['ELECTRIC_PROFILE_CUSTOMER_TOKEN'] raise ArgumentError, 'API URL is required' unless @api_url = ENV['ELECTRIC_PROFILE_API_URL'] @http_headers = { 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'Accept-Charset' => 'utf-8', 'User-Agent' => 'electric_profile_ruby', 'Profiling-Auth-Token' => @customer_token } end def fetch_questions uri = URI(@api_url + 'question') http_request = Net::HTTP::Get.new uri, @http_headers perform_request(uri, http_request) end def fetch_question(question_id) uri = URI(@api_url + 'question?id=' + question_id) http_request = Net::HTTP::Get.new uri, @http_headers perform_request(uri, http_request) end def create_question(question_attributes) uri = URI(@api_url + 'question') http_request = Net::HTTP::Post.new uri, @http_headers http_request.body = { "data" => question_attributes }.to_json perform_request(uri, http_request) end def update_question(question_attributes) uri = URI(@api_url + 'question') http_request = Net::HTTP::Put.new uri, @http_headers http_request.body = { "data" => question_attributes }.to_json perform_request(uri, http_request) end def fetch_profilers uri = URI(@api_url + 'profiler') http_request = Net::HTTP::Get.new uri, @http_headers perform_request(uri, http_request) end def fetch_profiler(profiler_id) uri = URI(@api_url + 'profiler?id=' + profiler_id) http_request = Net::HTTP::Get.new uri, @http_headers perform_request(uri, http_request) end def create_profiler(profiler_attributes) uri = URI(@api_url + 'profiler') http_request = Net::HTTP::Post.new uri, @http_headers http_request.body = { "data" => profiler_attributes }.to_json perform_request(uri, http_request) end def update_profiler(profiler_attributes) uri = URI(@api_url + 'profiler') http_request = Net::HTTP::Put.new uri, @http_headers http_request.body = { "data" => profiler_attributes }.to_json perform_request(uri, http_request) end private def perform_request(uri, http_request) use_ssl = @api_url.include? "https" http_response = Net::HTTP.start(uri.host, uri.port, use_ssl: use_ssl) do |http| http.request http_request end case http_response when Net::HTTPSuccess, Net::HTTPRedirection @data = JSON.parse http_response.body @successful = true else @error = "#{http_response.code}: #{http_response.body}" @successful = false end return @successful end end end