11# Client implementation for SerpApi.com
22#
33module SerpApi
4+
45 # Client for SerpApi.com
56 #
67 class Client
7- VERSION = '1.0.0' . freeze
8- BACKEND = 'serpapi.com' . freeze
8+ include Errors
99
10- # HTTP timeout in seconds (default: 120)
11- attr_accessor :timeout
10+ BACKEND = 'serpapi.com' . freeze
1211
13- # Default parameters provided in the constructor (hash)
14- attr_accessor :params
12+ # HTTP timeout requests
13+ attr_reader :timeout ,
14+ # Query parameters
15+ :params
1516
1617 # Constructor
1718 #
@@ -24,7 +25,7 @@ class Client
2425 # The params hash should contains the following optional field:
2526 # api_key [String] user secret API key
2627 # engine [String] search enginge selected
27- # timeout [Integer] HTTP read max timeout in seconds (default: 60s )
28+ # timeout [Integer] HTTP read max timeout in seconds (default: 120s )
2829 #
2930 # key can be either a symbol or a string.
3031 #
@@ -113,10 +114,10 @@ def build_url(endpoint, params)
113114 query = ( @params || { } ) . merge ( params || { } )
114115
115116 # set ruby client
116- query [ :source ] = 'serpapi-ruby:' << VERSION
117+ query [ :source ] = 'serpapi-ruby:' << SerpApi :: VERSION
117118
118119 # delete empty key/value
119- query . delete_if { | _ , value | value . nil? }
120+ query . compact!
120121
121122 # HTTP params encoding
122123 encoded_query = URI . encode_www_form ( query )
@@ -133,15 +134,17 @@ def build_url(endpoint, params)
133134 # @return decoded payload as JSON / Hash or String
134135 def get ( endpoint , decoder = :json , params = { } )
135136 url = build_url ( endpoint , params )
136- payload = URI ( url ) . open ( read_timeout : @read_timeout ) . read
137+ payload = URI ( url ) . open ( read_timeout : timeout ) . read
137138 decode ( payload , decoder )
138- rescue OpenURI ::HTTPError => e
139- data = JSON . parse ( e . io . read )
140- raise SerpApiException , "error: #{ data [ 'error' ] } from url: #{ url } " if data . key? ( 'error' )
141-
142- raise SerpApiException , "fail: get url: #{ url } response: #{ data } "
143- rescue => e
144- raise SerpApiException , "fail: get url: #{ url } caused by: #{ e } "
139+ rescue OpenURI ::HTTPError => err
140+ data = JSON . parse ( err . io . read )
141+ if data . key? ( 'error' )
142+ raise SerpApiException , "error: #{ data [ 'error' ] } from url: #{ url } "
143+ end
144+ raise SerpApiException , "fail: get url: #{ url } response: #{ data } "
145+ rescue => err
146+ raise SerpApiException , "fail: get url: #{ url } caused by: #{ err } "
147+ end
145148 end
146149
147150 # decode HTTP payload either as :json or :html
@@ -160,5 +163,4 @@ def decode(payload, decoder)
160163 raise SerpApiException , msg
161164 end
162165 end
163- end
164166end
0 commit comments