Skip to content

Commit d864aad

Browse files
committed
Set custom default user agent and allow user override
1 parent 5a72eaf commit d864aad

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

lib/opencage/geocoder.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
require 'opencage/geocoder/location'
22
require 'opencage/geocoder/request'
33
require 'opencage/error'
4+
require 'opencage/version'
45
require 'open-uri'
56
require 'json'
67

78
module OpenCage
89
class Geocoder
910
def initialize(default_options = {})
1011
@api_key = default_options.fetch(:api_key) { raise_error('401 Missing API key') }
12+
@user_agent = default_options.fetch(:user_agent) { "opencage-ruby/#{OpenCage::VERSION} Ruby/#{RUBY_VERSION}" }
1113
end
1214

1315
def geocode(location, options = {})
@@ -33,11 +35,15 @@ def reverse_geocode(lat, lng, options = {})
3335
private
3436

3537
def fetch(url)
36-
JSON.parse(URI(url).open.read)['results']
38+
JSON.parse(URI(url).open(headers).read)['results']
3739
rescue OpenURI::HTTPError => e
3840
raise_error(e)
3941
end
4042

43+
def headers
44+
{ 'User-Agent' => @user_agent }
45+
end
46+
4147
def raise_error(error)
4248
code = String(error).slice(0, 3)
4349
klass = OpenCage::Error::ERRORS[code.to_i]

spec/open_cage/geocoder_spec.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,4 +83,28 @@ def geo
8383
expect(geo.geocode('NOWHERE-INTERESTING')).to eql([])
8484
end
8585
end
86+
87+
describe 'user agent' do
88+
before do
89+
stub_request(:get, /api\.opencagedata\.com/)
90+
.to_return(body: '{}', status: 200)
91+
end
92+
93+
it 'uses a default user agent' do
94+
described_class.new(api_key: ENV.fetch('OPEN_CAGE_API_KEY'))
95+
.geocode('SOMEWHERE')
96+
97+
expect(WebMock).to have_requested(:get, /api\.opencagedata\.com/)
98+
.with(headers: { 'User-Agent' => "opencage-ruby/#{OpenCage::VERSION} Ruby/#{RUBY_VERSION}" })
99+
end
100+
101+
it 'allows a custom user agent to be set' do
102+
user_agent = 'my-app/1.0'
103+
described_class.new(api_key: ENV.fetch('OPEN_CAGE_API_KEY'), user_agent: user_agent)
104+
.geocode('SOMEWHERE')
105+
106+
expect(WebMock).to have_requested(:get, /api\.opencagedata\.com/)
107+
.with(headers: { 'User-Agent' => user_agent })
108+
end
109+
end
86110
end

0 commit comments

Comments
 (0)