Sha256: 3cc8a9af3a7fccf3d96aa4ea29194d5eaa7948e8bcd10c1d86ee86b426e2daf2

Contents?: true

Size: 1.38 KB

Versions: 3

Compression:

Stored size: 1.38 KB

Contents

module Ahub
  module APIHelpers
    require 'base64'

    def headers(username:'answerhub', password:'answerhub')
      encoded = "Basic #{::Base64.strict_encode64("#{username}:#{password}")}"

      {
        'Authorization' => encoded,
        'Accept' => "application/json",
        'Content-type' => "application/json",
      }
    end

    def admin_headers
      headers(username: Ahub::ADMIN_USER, password: Ahub::ADMIN_PASS)
    end

    def find(id)
      url = "#{base_url}/#{id}.json"

      new JSON.parse(RestClient.get(url, admin_headers), symbolize_names:true)
    rescue RestClient::ResourceNotFound => e
      nil
    end

    def find_all(params: nil, page: 1, pageSize: 30)
      url = "#{base_url}.json?page=#{page}&pageSize=#{pageSize}"

      if params
        params.each{|k,v| url << "&#{k}=#{URI.encode(v)}"}
      end

      JSON.parse(RestClient.get(url, admin_headers), symbolize_names:true)[:list].map do |node|
        new(node)
      end
    end

    def base_url
      class_name = name.gsub(/Ahub::/, '').downcase
      "#{Ahub::DOMAIN}/services/v2/#{class_name}"
    end

    def object_id_from_response(response)
      response.headers[:location].match(/(?<id>\d*)\.json/)[:id].to_i
    end

    private

    def make_post_call(url:, payload:, headers:)
      response = RestClient.post(url, payload.to_json, headers)
      find(object_id_from_response(response))
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ahub-0.1.17 lib/ahub/modules/api_helpers.rb
ahub-0.1.16 lib/ahub/modules/api_helpers.rb
ahub-0.1.15 lib/ahub/modules/api_helpers.rb