-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_service.rb
40 lines (29 loc) · 1.14 KB
/
client_service.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# frozen_string_literal: true
module Google
class ClientService
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) '\
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36'
BASE_SEARCH_URL = 'https://www.google.com/search'
def initialize(keyword:, lang: 'en')
@escaped_keyword = CGI.escape(keyword)
@uri = URI("#{BASE_SEARCH_URL}?q=#{@escaped_keyword}&hl=#{lang}&gl=#{lang}")
end
def call
result = HTTParty.get(@uri, { headers: { 'User-Agent' => USER_AGENT } })
return false unless valid_result? result
result
rescue HTTParty::Error, Timeout::Error, SocketError => e
Rails.logger.error "Error: Query Google with '#{@escaped_keyword}' thrown an error: #{e}".colorize(:red)
false
end
private
# Inspect Http response status code
# Any non 200 response code will be logged
def valid_result?(result)
return true if result&.response&.code == '200'
Rails.logger.warn "Warning: Query Google with '#{@escaped_keyword}' return status code #{result.response.code}"
.colorize(:yellow)
false
end
end
end