Sha256: 06ff2aad9b258731608c36906b3ee0a13b195ab3c7d2dc71a5c5056f807cd129

Contents?: true

Size: 1.63 KB

Versions: 2

Compression:

Stored size: 1.63 KB

Contents

require 'active_support'
require 'json'
require 'httparty'
require 'digest/md5'

module Masheri
  class Client
    TEST_HOST = 'api.sandbox.mashery.com'
    PRODUCTION_HOST = 'api.mashery.com'

    def self.from_yaml(yaml_file)
      config = YAML.load_file(yaml_file)
      new(config["site_id"], config["key"], config["secret"])
    end

    attr_accessor :uri, :key, :secret

    def initialize(site_id, key, secret)
      host    = Masheri.test_mode ? TEST_HOST : PRODUCTION_HOST
      @uri    = "http://#{host}/v2/json-rpc/#{site_id}"
      @key    = key
      @secret = secret
    end

    def echo(value)
      call_remote('test.echo', value)
    end

    def perform(params)
      # all calls are synchronous, so id in request and response will always be 1
      if Masheri.logger
        Masheri.logger.debug("Calling query with params #{params.inspect} on URI #{full_url}")
      end

      response = RestClient.post(full_url, params.to_json, {
                                   "Content-Type"   => "application/json",
                                   "Accept"         => "text/plain",
                                   "Content-Length" => params.size
                                 })

      JSON.parse response
    end

    def query(string)
      call_remote("object.query", params: string)
    end

    def call_remote(method, opts = {})
      perform({'method' => method, 'params'=> [opts[:params]], 'id' => 1})
    end

    def create(type, params)
      call_remote("#{type}.create")
    end

    protected
    def full_url
      "#{@uri}?apikey=#{@key}&sig=#{Digest::MD5.hexdigest(@key + @secret + Time.now.to_f.to_i.to_s)}"
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
masheri-0.3.1 lib/masheri/client.rb
masheri-0.2.0 lib/masheri/client.rb