Sha256: 135b7c5adc4141229b652759259a732cc0501f7d5d09bd9a52911490a6492448

Contents?: true

Size: 1.67 KB

Versions: 11

Compression:

Stored size: 1.67 KB

Contents

require 'rest_client'
require 'singleton'

module Flydata
  FLYDATA_API_HOST = ENV['FLYDATA_API_HOST'] || '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 = "http://#{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 = "http://#{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 = "http://#{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

11 entries across 11 versions & 1 rubygems

Version Path
flydata-0.0.2 lib/flydata/api_client.rb
flydata-0.0.2.rc1 lib/flydata/api_client.rb
flydata-0.0.1.2011102901 lib/flydata/api_client.rb
flydata-0.0.1.nc2 lib/flydata/api_client.rb
flydata-0.0.1.nc1 lib/flydata/api_client.rb
flydata-0.0.1.2011102602 lib/flydata/api_client.rb
flydata-0.0.1.2011102601 lib/flydata/api_client.rb
flydata-0.0.1.2011102401 lib/flydata/api_client.rb
flydata-0.0.1.2011102303 lib/flydata/api_client.rb
flydata-0.0.1.2011102302 lib/flydata/api_client.rb
flydata-0.0.1.2011102301 lib/flydata/api_client.rb