Skip to content

Commit

Permalink
Merge pull request #2 from pexels/local-headers
Browse files Browse the repository at this point in the history
Allow headers to be sent to the API to be defined locally
  • Loading branch information
dvandersluis authored Apr 9, 2021
2 parents 7510ceb + 4bc87c2 commit 26c1346
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.gems.up.to.date
.env
*.gem
.headers
15 changes: 15 additions & 0 deletions lib/pexels.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ module Pexels

class << self
attr_reader :api_base_url, :api_version

# Local headers can be defined inside a `.headers` file at the project root,
# with the following format:
#
# header1=value
# header2=value
# etc.
#
def local_headers
@local_headers ||= if File.exist?('.headers')
File.read('.headers').split.to_h { |header| header.split('=') }
else
{}
end
end
end
end

Expand Down
13 changes: 7 additions & 6 deletions lib/pexels/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ class Pexels::Client
attr_reader :api_key,
:ratelimit_remaining


def initialize(api_key = ENV['PEXELS_API_KEY'])
@api_key = api_key
end
Expand All @@ -19,18 +18,20 @@ def videos

def request(path, method: 'GET', params: {})
url = File.join(Pexels.api_base_url, path)
puts "Requesting #{url}" if ENV['DEBUG']
headers = {
'Authorization' => api_key
}.merge(Pexels.local_headers)

puts "Requesting #{url} with #{headers}" if ENV['DEBUG']

results = Requests.request(
method,
url,
params: params,
headers: {
'Authorization' => api_key
}
headers: headers
)

@ratelimit_remaining = results.headers['x-ratelimit-remaining'].first.to_i
@ratelimit_remaining = results.headers['x-ratelimit-remaining']&.first&.to_i

return JSON.parse(results.body)
rescue StandardError => exception
Expand Down

0 comments on commit 26c1346

Please sign in to comment.