Sha256: 05fd6bdbeb2cc21f65c9563bca681e6f52b67168dd22f605c755c869034df926

Contents?: true

Size: 1.66 KB

Versions: 3

Compression:

Stored size: 1.66 KB

Contents

require 'rest_client'
require 'singleton'

module Flydata
  FLYDATA_API_HOST = ENV['FLYDATA_API_HOST'] || 'https://flydata.co'

  class ApiClient
    include Singleton
    attr_reader :response
    attr_accessor :credentials

    def initialize
      @credentials = Flydata::Credentials.new
    end

    # row level api
    def post(path, params=nil)
      uri = "#{FLYDATA_API_HOST}#{path}"
      resource = RestClient::Resource.new(uri, resource_opts)
      @response = resource.post(params, :accept => :json)
      handle_response response
    end
    def put(path, params=nil)
      uri = "#{FLYDATA_API_HOST}#{path}"
      resource = RestClient::Resource.new(uri, resource_opts)
      @response = resource.put(params, :accept => :json)
      handle_response response
    end
    def get(path)
      uri = "#{FLYDATA_API_HOST}#{path}"
      resource = RestClient::Resource.new(uri, resource_opts)
      @response = resource.get(:accept => :json)
      handle_response response
    end

    # high level api
    def method_missing(cls_name, *args, &block)
      method_name = args.shift.to_s
      api_cls = "Flydata::Api::#{cls_name.to_s.camelize}".constantize
      api_cls.new(self)
    end
    def respond_to_missing?(method_name, include_private=false); true end

    private
    def handle_response(response)
      json_response = JSON.parse(response)
      if json_response.class == Hash and json_response["success"] == false
        err_msg = json_response['errors'] ? json_response['errors'].to_s : "Unkown error."
        raise err_msg
      end
      json_response
    end
    def resource_opts
      {:user => @credentials.user, :password => @credentials.password}
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
flydata-0.0.2.3 lib/flydata/api_client.rb
flydata-0.0.2.2 lib/flydata/api_client.rb
flydata-0.0.2.1 lib/flydata/api_client.rb