Skip to content

Instantly share code, notes, and snippets.

@asqd
Created March 22, 2018 08:32
Show Gist options
  • Save asqd/a898dc48b1bd8d30b6cc8877207f216d to your computer and use it in GitHub Desktop.
Save asqd/a898dc48b1bd8d30b6cc8877207f216d to your computer and use it in GitHub Desktop.
GeoSmartRequester
module GeoSmart
@base_path = "new_url"
@token = "token"
@legacy_path = "old_url"
class << self
attr_accessor :base_path, :token, :legacy_path
end
class Address
include ActiveModel::Serialization
def fields
instance_variables
end
def attributes
instance_values
end
def initialize(attributes={})
attributes.each do |key, value|
self.class.send(:attr_accessor, key.downcase.to_sym)
self.instance_variable_set("@#{key.downcase.to_sym}", value)
end
end
def self.search(params={})
json = GeoSmart::Request.new("api-buildings/?token=#{token}&#{query_params(params)}").fetch
json["items"].map{ |resource| self.new(resource) }
end
def self.json(params={})
json = GeoSmart::Request.new("api-buildings/?token=#{token}&#{query_params(params)}").fetch
json["items"].map{ |resource| self.new(resource) }
end
def self.find(id, params={})
json = GeoSmart::Request.new("api-buildings/#{id}/view?token=#{token}&#{query_params(params)}").fetch
self.new(json)
end
def self.legacy_find(id)
json = GeoSmart::Request.new("address/view/#{id}", legacy=true).fetch
self.new(json)
end
def self.legacy_search(params={})
params[:query] = params[:query].gsub('ё','е')
json = GeoSmart::Request.new("address/index?search=#{params[:query]}", legacy=true).fetch
json.map{ |resource| self.new(resource) }
end
def self.token
GeoSmart::Request.token
end
def self.query_params(params)
params[:q] = params[:query] if params[:query]
params.except(:query).to_query
end
end
class Request
attr_accessor :method, :params, :legacy
def initialize params, legacy=false
@params = params
@legacy = legacy
end
def fetch
body = get_content
json = JSON.parse(body)
json
end
def get_content
http = Net::HTTP.new(url.host, url.port)
http.request(Net::HTTP::Get.new(request_uri)).body
end
private
def url
if legacy
URI.parse(GeoSmart.legacy_path + URI.encode(@params.to_s))
else
URI.parse(GeoSmart.base_path + URI.encode(@params.to_s))
end
end
def request_uri
if url.request_uri.length > 4048
url.request_uri.chars.to_a.take(4047).join
else
url.request_uri
end
end
def self.token
GeoSmart.token
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment