Permalink
Browse files

read API key from ~/.echonest/api_key

  • Loading branch information...
1 parent c35bf0b commit 57924a1b0ba34de4a1acbbca41a8b52687f04fe2 @youpy committed Jan 9, 2012
Showing with 30 additions and 3 deletions.
  1. +1 −1 lib/echonest.rb
  2. +12 −2 lib/echonest/api.rb
  3. +17 −0 spec/api_spec.rb
View
@@ -12,7 +12,7 @@
require 'pathname'
-def Echonest(api_key) Echonest::Api.new(api_key) end
+def Echonest(api_key = nil) Echonest::Api.new(api_key) end
module Echonest
DIRECTORY = Pathname.new("~/.echonest").expand_path
View
@@ -16,8 +16,8 @@ class Error < StandardError; end
attr_reader :user_agent
- def initialize(api_key)
- @api_key = api_key
+ 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
@@ -69,6 +69,16 @@ def request(name, method, params, file = nil)
rescue HTTPClient::BadResponseError => e
raise Error.new('%s: %s' % [name, e.message])
end
+
+ def self.api_key_file
+ DIRECTORY + 'api_key'
+ end
+
+ private
+
+ def read_api_key_from_file
+ self.class.api_key_file.read.chomp
+ end
end
module ApiMethods
View
@@ -1,12 +1,29 @@
$:.unshift File.dirname(__FILE__)
require 'spec_helper'
+require 'tempfile'
describe Echonest::Api do
before do
@api = Echonest::Api.new('8TPE3VC60ODJTNTFE')
end
+ it "should have a filename for api key" do
+ Echonest::Api.api_key_file.to_s.should eql(Pathname('~/.echonest/api_key').expand_path.to_s)
+ end
+
+ it "should read api key from file" do
+ file = Tempfile.new('api_key')
+ file.write('XXXXX')
+ file.flush
+
+ Echonest::Api.should_receive(:api_key_file).and_return(Pathname(file.path))
+
+ api = Echonest::Api.new
+
+ api.instance_variable_get('@api_key').should eql('XXXXX')
+ end
+
it "should build parameters" do
params = @api.build_params(:id => 'TRXXHTJ1294CD8F3B3')
params.keys.size.should eql(3)

0 comments on commit 57924a1

Please sign in to comment.