Class: MusixMatch::API::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/musix_match/api/base.rb

Direct Known Subclasses

Feedback, Finder, Search, TrackChart

Constant Summary collapse

API_URL =
'http://api.musixmatch.com/ws/1.1'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.api_keyObject



14
15
16
# File 'lib/musix_match/api/base.rb', line 14

def self.api_key
  class_variable_defined?("@@api_key") ? @@api_key : nil
end

.api_key=(value) ⇒ Object



10
11
12
# File 'lib/musix_match/api/base.rb', line 10

def self.api_key=(value)
  @@api_key = value        
end

.get(method, params = {}) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/musix_match/api/base.rb', line 30

def self.get(method, params={})
  raise APIKeyNotSpecifiedException.new('You must specify the API key. MusixMatch::API::Base.api_key = "YOUR_API_KEY"') if api_key.nil?
  response = perform_get_request(url_for(method, params))
  parsed_response = case response.parsed_response
  when Hash
    response.parsed_response
  when String
    JSON.parse(response.parsed_response)
  end
  case  parsed_response['message']['header']['status_code']
    when 401 then raise AuthenticationFailedException.new('Authentication failed, probably because of a bad API key')
    when 402 then raise APILimitReachedException.new('A limit was reached, either you exceeded per hour requests limits or your balance is insufficient')
  end
  parsed_response
end

.perform_get_request(url) ⇒ Object



46
47
48
# File 'lib/musix_match/api/base.rb', line 46

def self.perform_get_request(url)
  HTTParty.get(url)
end

.url_for(method, params = {}) ⇒ Object



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

def self.url_for(method, params={})
  URI.escape("#{API_URL}/#{url_path_for(method, params)}")
end

.url_path_for(method, params = {}) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/musix_match/api/base.rb', line 22

def self.url_path_for(method, params={})
  params.delete('format')
  params.delete('apikey')
  params.merge!({ :apikey => api_key, :format => 'json' })
  url_params = params.collect{|k, v| "#{k}=#{v}"}.join('&')
  "#{method}?#{url_params}"
end

Instance Method Details

#api_keyObject



50
51
52
# File 'lib/musix_match/api/base.rb', line 50

def api_key    
  self.class.api_key
end

#get(method, params = {}) ⇒ Object



54
55
56
# File 'lib/musix_match/api/base.rb', line 54

def get(method, params={})
  self.class.get(method, params)
end