Skip to content

Commit

Permalink
Merge pull request sferik#338 from DanKnox/validate_credential_config…
Browse files Browse the repository at this point in the history
…uration

Ensure credentials set in Twitter.configure are of a valid type.
  • Loading branch information
sferik committed Dec 30, 2012
2 parents 1a4d9f3 + 9af3d73 commit be08002
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
21 changes: 21 additions & 0 deletions lib/twitter/configurable.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require 'twitter/error/configuration_error'

module Twitter
module Configurable
attr_writer :consumer_key, :consumer_secret, :oauth_token, :oauth_token_secret
Expand All @@ -21,8 +23,12 @@ def keys
end

# Convenience method to allow configuration options to be set in a block
#
# @raise [Twitter::Error::ConfigurationError] Error is raised when supplied
# twitter credentials are not a String or Symbol.
def configure
yield self
validate_credential_type!
self
end

Expand Down Expand Up @@ -61,5 +67,20 @@ def options
Hash[Twitter::Configurable.keys.map{|key| [key, instance_variable_get(:"@#{key}")]}]
end

# Ensures that all credentials set during configuration are of a
# valid type. Valid types are String and Symbol.
#
# @raise [Twitter::Error::ConfigurationError] Error is raised when
# supplied twitter credentials are not a String or Symbol.
def validate_credential_type!
credentials.each do |credential, value|
next if value.nil?

unless value.is_a?(String) || value.is_a?(Symbol)
raise(Error::ConfigurationError, "Invalid #{credential} specified: #{value} must be a string or symbol.")
end
end
end

end
end
8 changes: 8 additions & 0 deletions lib/twitter/error/configuration_error.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
require 'twitter/error'

module Twitter
class Error
class ConfigurationError < ::ArgumentError
end
end
end
24 changes: 24 additions & 0 deletions spec/twitter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,30 @@
expect(Twitter.instance_variable_get(:"@#{key}")).to eq key
end
end

context "when invalid credentials are provided" do
it "raises a ConfigurationError exception" do
expect {
Twitter.configure do |config|
config.consumer_key = [12345, 54321]
config.consumer_secret = 'valid_data'
end
}.to raise_exception(Twitter::Error::ConfigurationError)
end
end

context "when no credentials are provided" do
it "does not raise an exception" do
expect {
Twitter.configure do |config|
config.consumer_key = nil
config.consumer_secret = nil
config.oauth_token = nil
config.oauth_token_secret = nil
end
}.to_not raise_exception(Twitter::Error::ConfigurationError)
end
end
end

describe ".credentials?" do
Expand Down

0 comments on commit be08002

Please sign in to comment.