Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set custom default user agent and allow user override #31

Merged
merged 1 commit into from
Feb 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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