Class: CUI8Tracks::API

Inherits:
Object
  • Object
show all
Includes:
Thing
Defined in:
lib/cui8tracks/api.rb

Constant Summary collapse

API_KEY =
'3bed6bc564136c299324e205ffaf3fa1b44f094e'

Instance Attribute Summary

Attributes included from Thing

#session

Instance Method Summary collapse

Methods included from Thing

#api, #data, #id, #info, #logger, #method_missing, #notify, #path, #set

Constructor Details

#initialize(username, password) ⇒ API

Returns a new instance of API.



6
7
8
9
10
# File 'lib/cui8tracks/api.rb', line 6

def initialize(username, password)
  @username = username
  @password = password
  @logged_in = false
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class CUI8Tracks::Thing

Instance Method Details

#get(path, param = { }) ⇒ Object



53
54
55
# File 'lib/cui8tracks/api.rb', line 53

def get(path, param = { })
  http_request(Net::HTTP::Get, path, param)
end

#http_request(klass, path, param = { }) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/cui8tracks/api.rb', line 23

def http_request(klass, path, param = { })
  path += '.json' unless path  =~ /\.json$/
  logger.debug "#{klass.to_s.split(/::/).last} #{path} #{param.inspect}"
  param[:api_key] = API_KEY
  port = param.delete(:https) ? 443 : 80 # XXX
  param_str = to_param_str(param)
  req = klass == Net::HTTP::Post ? klass.new(path) : klass.new(path + '?' + param_str)
  req.basic_auth(@username, @password) if @logged_in
  proxy_host, proxy_port = (ENV["http_proxy"] || ENV["HTTP_PROXY"] || '').sub(/http:\/\//, '').split(':')
  connection = Net::HTTP::Proxy(proxy_host, proxy_port).new('8tracks.com', port)
  connection.use_ssl = true if port == 443
  res = connection.start do |http|
    if req.kind_of? Net::HTTP::Post
      http.request(req, param_str)
    else
      http.request(req)
    end
  end
  json_data = JSON.parse(res.body)
  logger.debug json_data.inspect
  case res.code
  when '200'
    json_data
  else
    # XXX
    pp res
    raise 'api'
  end
end

#loginObject



12
13
14
15
16
# File 'lib/cui8tracks/api.rb', line 12

def 
  return if @logged_in
  res = post('/sessions', :login => @username, :password => @password, :https => true)
  @logged_in = true if res['logged_in']
end

#post(path, param = { }) ⇒ Object



57
58
59
# File 'lib/cui8tracks/api.rb', line 57

def post(path, param = { })
  http_request(Net::HTTP::Post, path, param)
end

#to_param_str(hash = { }) ⇒ Object

Raises:

  • (ArgumentError)


18
19
20
21
# File 'lib/cui8tracks/api.rb', line 18

def to_param_str(hash = { })
  raise ArgumentError, 'Argument must be a Hash object' unless hash.is_a?(Hash)
  hash.to_a.map{|i| i[0].to_s + '=' + CGI.escape(i[1].to_s) }.join('&')
end