Class: GCoder::GeocodingAPI::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/gcoder/geocoding_api.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(query, options = {}) ⇒ Request

Returns a new instance of Request.



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/gcoder/geocoding_api.rb', line 21

def initialize(query, options = {})
  unless query
    raise Errors::BlankRequestError, "query cannot be nil"
  end
  unless query.is_a?(String)
    raise Errors::MalformedQueryError, "query must be String, not: #{query.class}"
  end
  @config = Config.merge(options)
  @query = query
  validate_state!
end

Class Method Details

.get(query, options = {}) ⇒ Object



15
16
17
18
19
# File 'lib/gcoder/geocoding_api.rb', line 15

def self.get(query, options = {})
  response = new(query, options).get
  response.validate!
  response.to_h
end

Instance Method Details

#getObject



51
52
53
54
55
56
57
58
59
# File 'lib/gcoder/geocoding_api.rb', line 51

def get
  return @json_response if @json_response
  Timeout.timeout(@config[:gmaps_api_timeout]) do
    Response.new(self)
  end
rescue Timeout::Error
  raise Errors::RequestTimeoutError, 'The query timed out at ' \
  "#{@config[:gmaps_api_timeout]} second(s)"
end

#http_getObject



61
62
63
# File 'lib/gcoder/geocoding_api.rb', line 61

def http_get
  open(uri).read
end

#paramsObject



33
34
35
# File 'lib/gcoder/geocoding_api.rb', line 33

def params
  BASE_PARAMS.merge(:key => @config[:gmaps_api_key], :q => query)
end

#queryObject



43
44
45
# File 'lib/gcoder/geocoding_api.rb', line 43

def query
  @config[:append_query] ? "#{@query} #{@config[:append_query]}" : @query
end

#to_paramsObject



37
38
39
40
41
# File 'lib/gcoder/geocoding_api.rb', line 37

def to_params
  params.inject([]) do |array, (key, value)|
    array << "#{uri_escape key}=#{uri_escape value}"
  end.join('&')
end

#uriObject



47
48
49
# File 'lib/gcoder/geocoding_api.rb', line 47

def uri
  [BASE_URI, '?', to_params].join
end