Class: Echonest::Api

Inherits:
Object
  • Object
show all
Includes:
TraditionalApiMethods
Defined in:
lib/echonest/api.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

BASE_URL =
'http://developer.echonest.com/api/v4/'
USER_AGENT =
'%s/%s' % ['ruby-echonest', ::Echonest::VERSION]

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from TraditionalApiMethods

included

Constructor Details

#initialize(api_key) ⇒ Api

Returns a new instance of Api.



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

def initialize(api_key)
  @api_key = api_key
  @user_agent = HTTPClient.new(:agent_name => USER_AGENT)
end

Instance Attribute Details

#user_agentObject (readonly)

Returns the value of attribute user_agent.



16
17
18
# File 'lib/echonest/api.rb', line 16

def user_agent
  @user_agent
end

Instance Method Details

#build_params(params) ⇒ Object



27
28
29
30
31
# File 'lib/echonest/api.rb', line 27

def build_params(params)
  params = params.
    merge(:format => 'json').
    merge(:api_key => @api_key)
end

#request(name, method, params, file = nil) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/echonest/api.rb', line 33

def request(name, method, params, file = nil)
  if file
    query = build_params(params).sort_by do |param|
      param[0].to_s
    end.inject([]) do |m, param|
      m << [URI.encode(param[0].to_s), URI.encode(param[1])].join('=')
    end.join('&')

    uri = URI.join(BASE_URL, name.to_s)
    uri.query = query

    response_body = @user_agent.__send__(
      method.to_s + '_content',
      uri,
      file.read,
      {
        'Content-Type' => 'application/octet-stream'
      })
  else
    response_body = @user_agent.__send__(
      method.to_s + '_content',
      URI.join(BASE_URL, name.to_s),
      build_params(params))
  end

  response = Response.new(response_body)
  unless response.success?
    raise Error.new(response.status.message)
  end

  response
rescue HTTPClient::BadResponseError => e
  raise Error.new('%s: %s' % [name, e.message])
end

#trackObject



23
24
25
# File 'lib/echonest/api.rb', line 23

def track
  ApiMethods::Track.new(self)
end