Class: Echonest::Api

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

Defined Under Namespace

Classes: Error, UnsupportedFiletypeError

Constant Summary collapse

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from TraditionalApiMethods

included

Constructor Details

#initialize(api_key = nil) ⇒ Api

Returns a new instance of Api.



20
21
22
23
24
25
26
27
# File 'lib/echonest/api.rb', line 20

def initialize(api_key = nil)
  @api_key = api_key || read_api_key_from_file
  @user_agent = HTTPClient.new(:agent_name => USER_AGENT)

  # for big files
  @user_agent.send_timeout = 60 * 30
  @user_agent.receive_timeout = 60 * 10
end

Instance Attribute Details

#user_agentObject (readonly)

Returns the value of attribute user_agent.



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

def user_agent
  @user_agent
end

Class Method Details

.api_key_fileObject



74
75
76
# File 'lib/echonest/api.rb', line 74

def self.api_key_file
  DIRECTORY + 'api_key'
end

Instance Method Details

#build_params(params) ⇒ Object



33
34
35
36
37
# File 'lib/echonest/api.rb', line 33

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

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



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
67
68
69
70
71
72
# File 'lib/echonest/api.rb', line 39

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 << [CGI.escape(param[0].to_s), CGI.escape(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



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

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