Sha256: 03a37d323e846fab28f1c6be03fcbcdbe90480364268f50b42dcbe1e1ae9f290

Contents?: true

Size: 1.83 KB

Versions: 1

Compression:

Stored size: 1.83 KB

Contents

module Namely
  class ResourceGateway
    def initialize(options)
      @access_token = options.fetch(:access_token)
      @endpoint = options.fetch(:endpoint)
      @resource_name = options.fetch(:resource_name)
      @subdomain = options.fetch(:subdomain)
    end

    def json_index
      get("/#{endpoint}", limit: :all)[resource_name]
    end

    def json_show(id)
      get("/#{endpoint}/#{id}")[resource_name].first
    end

    def show_head(id)
      head("/#{endpoint}/#{id}")
    end

    def create(attributes)
      response = post(
        "/#{endpoint}",
        endpoint => [attributes]
      )
      extract_id(response)
    end

    def update(id, changes)
      put("/#{endpoint}/#{id}", endpoint => [changes])
    end

    private

    attr_reader :access_token, :endpoint, :resource_name, :subdomain

    def url(path)
      "https://#{subdomain}.namely.com/api/v1#{path}"
    end

    def extract_id(response)
      JSON.parse(response)[endpoint].first["id"]
    rescue StandardError => e
      raise(
        FailedRequestError,
        "Couldn't parse \"id\" from response: #{e.message}"
      )
    end

    def get(path, params = {})
      params.merge!(access_token: access_token)
      JSON.parse(RestClient.get(url(path), accept: :json, params: params))
    end

    def head(path, params = {})
      params.merge!(access_token: access_token)
      RestClient.head(url(path), accept: :json, params: params)
    end

    def post(path, params)
      params.merge!(access_token: access_token)
      RestClient.post(
        url(path),
        params.to_json,
        accept: :json,
        content_type: :json,
      )
    end

    def put(path, params)
      params.merge!(access_token: access_token)
      RestClient.put(
        url(path),
        params.to_json,
        accept: :json,
        content_type: :json
      )
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
namely-0.0.1 lib/namely/resource_gateway.rb