Class: Echonest::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/echonest/connection.rb

Instance Method Summary collapse

Constructor Details

#initialize(base_url) ⇒ Connection

Returns a new instance of Connection.



6
7
8
# File 'lib/echonest/connection.rb', line 6

def initialize(base_url)
  @base_url = base_url
end

Instance Method Details

#boundaryObject



62
63
64
# File 'lib/echonest/connection.rb', line 62

def boundary
  '----BOUNDARYBOUNDARY----'
end

#get(resource, args = nil) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/echonest/connection.rb', line 10

def get(resource, args = nil)
  url = url(resource.to_s)

  if args
    url.query = query(args)
  end

  req = make_request(url, 'get')

  request(req, url)
end

#make_request(uri, method) ⇒ Object



78
79
80
81
82
83
# File 'lib/echonest/connection.rb', line 78

def make_request(uri, method)
  req = (method == 'post' ? Net::HTTP::Post : Net::HTTP::Get).new(uri.request_uri)
  req['User-Agent'] = user_agent

  req
end

#post(resource, args = nil) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/echonest/connection.rb', line 22

def post(resource, args = nil)
  url = url(resource.to_s)
  req = make_request(url, 'post')

  if args
    data = post_data(args)
    req['Content-Length'] = data.size.to_s
    req['Content-Type'] = "multipart/form-data; boundary=#{boundary}"
  end

  request(req, url, data)
end

#post_data(params) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/echonest/connection.rb', line 39

def post_data(params)
  data = params.inject([]) do |memo, param|
    name, value = param

    memo << "--#{boundary}"

    if name.to_s == 'file'
      memo << "Content-Disposition: form-data; name=\"#{name}\"; filename=\"file.mp3\""
      memo << "Content-Type: application/octet-stream"
    else
      memo << "Content-Disposition: form-data; name=\"#{name}\""
    end

    memo << ''
    memo << value
  end

  data << "--#{boundary}--"
  data << ''

  data.join("\r\n")
end

#query(params) ⇒ Object



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

def query(params)
  params.map { |k,v| "%s=%s" % [CGI.escape(k.to_s), CGI.escape(v.to_s)] }.join("&")
end

#request(req, url, data = nil) ⇒ Object



66
67
68
69
70
71
72
# File 'lib/echonest/connection.rb', line 66

def request(req, url, data = nil)
  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = (url.port == 443)

  res = http.start() { |conn| conn.request(req, data) }
  res.body
end

#url(path) ⇒ Object



35
36
37
# File 'lib/echonest/connection.rb', line 35

def url(path)
  URI.join(@base_url, path)
end

#user_agentObject



85
86
87
# File 'lib/echonest/connection.rb', line 85

def user_agent
  '%s/%s' % ['ruby-echonest', VERSION]
end