Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[Ruby - RailsアプリをHerokuへデプロイ後、ぐるなびAPIが検索結果を返さない|teratail](https://teratail.com/questions/203712)
# frozen_string_literal: true
require 'net/http'
require 'uri'
require 'json'
require 'logger'
require 'kaminari'
class GuruNaviApi
API_KEY = ENV['GNAVI_API_KEY']
BASE_URL =
if Time.now > Time.new(2019, 9, 3)
'https://api.gnavi.co.jp/api/announcement/20180903/?'
else
'https://api.gnavi.co.jp/RestSearchAPI/v3/?'
end
private_constant :API_KEY
class << self
def search_restaurants(**args)
response = request_query(**args)
convert_to_kaminari_pagination(response)
end
private
def request_query(name:, freeword:, offset_page:)
params =
URI.encode_www_form(
keyid: API_KEY,
name: name,
freeword: freeword,
offset_page: offset_page
)
target_url = URI.parse("#{BASE_URL}#{params}")
Net::HTTP.new(target_url.host, target_url.port).yield_self do |http|
http.use_ssl = true
http.open_timeout = 5
http.read_timeout = 30
http.get(target_url.request_uri)
end
rescue TimeoutError => e
logger.error(e.message)
end
def convert_to_kaminari_pagination(response)
log_when_http_errors(response) do
results =
log_when_json_parse_error { JSON.parse(response.body, symbolize_names: true) }
limit_of_paginate =
if results[:total_hit_count].to_i <= 1_000
results[:total_hit_count]
else
1_000
end
Kaminari.paginate_array(results[:rest], total_count: limit_of_paginate)
.page(results[:page_offset])
.per(results[:hit_per_page])
end
end
def log_when_json_parse_error
yield
rescue JSON::ParserError => e
logger.error(e.message)
rescue StandardError => e
logger.error(e.message)
end
def log_when_http_errors(response)
case response
when Net::HTTPSuccess
yield
when Net::HTTPRedirection
logger.warn("Redirection: code=#{response.code} message=#{response.message}")
else
logger.error("HTTP ERROR: code=#{response.code} message=#{response.message}")
end
end
def logger
Logger.new(Rails.root.join('log', 'webapi.log'))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment