class PhantRb::Client

Public Class Methods

new(public_key, fields, opts = {}) click to toggle source
# File lib/phant_rb.rb, line 8
def initialize(public_key, fields, opts = {})
  @opts = {
    base_url: 'http://data.sparkfun.com/'
  }.merge(opts)
  @fields = fields
  @public_key = public_key
end

Public Instance Methods

clear() click to toggle source
# File lib/phant_rb.rb, line 34
def clear
  conn = rest_conn 'input'
  response = conn.delete
  Hashie::Mash.new(JSON.parse(response.body))
end
get(params = {}) click to toggle source
# File lib/phant_rb.rb, line 22
def get(params = {})
  conn = rest_conn 'output', params
  response = conn.get
  JSON.parse response.body
end
log(*data) click to toggle source
# File lib/phant_rb.rb, line 16
def log(*data)
  conn = rest_conn 'input'
  @last_response = conn.post URI.encode_www_form(@fields.zip(data))
  Hashie::Mash.new(JSON.parse(@last_response.body))
end
rate_limits() click to toggle source
# File lib/phant_rb.rb, line 40
def rate_limits
  unless !@last_response.nil? && @last_response.headers.has_key?(:x_rate_limit_remaining)
    raise "No rate limit headers found. PhantRb::Client#log must be called before this."
  end
  Hashie::Mash.new(@last_response.headers)
end
stats() click to toggle source
# File lib/phant_rb.rb, line 28
def stats
  conn = rest_conn 'stats'
  response = conn.get
  Hashie::Mash.new(JSON.parse(response.body))
end

Private Instance Methods

rest_conn(type, params = nil) click to toggle source
# File lib/phant_rb.rb, line 48
def rest_conn(type, params = nil)
  url = case type
        when 'stats' then URI.join @opts[:base_url], "/output/", "#{@public_key}/stats.json"
        else
          if params.nil?
            URI.join @opts[:base_url], "/#{type}/", "#{@public_key}.json"
          else
            URI.join @opts[:base_url], "/#{type}/", "#{@public_key}.json?" + URI.encode_www_form(params)
          end
        end

  RestClient::Resource.new url.to_s,
    {:headers => {'Phant-Private-Key' => @opts[:private_key]}}
end