Skip to content

Commit

Permalink
Set custom default user agent and allow user override
Browse files Browse the repository at this point in the history
  • Loading branch information
sbscully committed Feb 2, 2025
1 parent 5a72eaf commit d864aad
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lib/opencage/geocoder.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
require 'opencage/geocoder/location'
require 'opencage/geocoder/request'
require 'opencage/error'
require 'opencage/version'
require 'open-uri'
require 'json'

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

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

def fetch(url)
JSON.parse(URI(url).open.read)['results']
JSON.parse(URI(url).open(headers).read)['results']
rescue OpenURI::HTTPError => e
raise_error(e)
end

def headers
{ 'User-Agent' => @user_agent }
end

def raise_error(error)
code = String(error).slice(0, 3)
klass = OpenCage::Error::ERRORS[code.to_i]
Expand Down
24 changes: 24 additions & 0 deletions spec/open_cage/geocoder_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,28 @@ def geo
expect(geo.geocode('NOWHERE-INTERESTING')).to eql([])
end
end

describe 'user agent' do
before do
stub_request(:get, /api\.opencagedata\.com/)
.to_return(body: '{}', status: 200)
end

it 'uses a default user agent' do
described_class.new(api_key: ENV.fetch('OPEN_CAGE_API_KEY'))
.geocode('SOMEWHERE')

expect(WebMock).to have_requested(:get, /api\.opencagedata\.com/)
.with(headers: { 'User-Agent' => "opencage-ruby/#{OpenCage::VERSION} Ruby/#{RUBY_VERSION}" })
end

it 'allows a custom user agent to be set' do
user_agent = 'my-app/1.0'
described_class.new(api_key: ENV.fetch('OPEN_CAGE_API_KEY'), user_agent: user_agent)
.geocode('SOMEWHERE')

expect(WebMock).to have_requested(:get, /api\.opencagedata\.com/)
.with(headers: { 'User-Agent' => user_agent })
end
end
end

0 comments on commit d864aad

Please sign in to comment.