Answer the question
In order to leave comments, you need to log in
How to make the right exception?
Hey! Guys, such a question: I use Yandex api to display a marker on the map, at the address from the form.
I wrote this method that receives json on request to Yandex, parses it into a hash and gets the coordinates
def get_coordinates
addr = URI.encode(URI.decode(self.address))
http = "http://geocode-maps.yandex.ru/1.x/?format=json&geocode=#{addr}"
json = RestClient.get(http)
parced_json = ActiveSupport::JSON.decode(json)
parced_json["response"]["GeoObjectCollection"]["featureMember"][0]["GeoObject"]["Point"]["pos"]
end
before_save :set_coordinates
def set_coordinates
if address_changed?
self.coordinates = get_coordinates
end
end
def get_coordinates
begin
addr = URI.encode(URI.decode(self.address))
http = "http://geocode-maps.yandex.ru/1.x/?format=json&geocode=#{addr}"
json = RestClient.get(http)
parced_json = ActiveSupport::JSON.decode(json)
parced_json["response"]["GeoObjectCollection"]["featureMember"][0]["GeoObject"]["Point"]["pos"]
rescue NoMethodError
self.errors.add(:coordinates)
end
end
@messages={:coordinates=>["is invalid"]}>
Answer the question
In order to leave comments, you need to log in
def get_coordinates
begin
addr = URI.encode(URI.decode(self.address))
http = "http://geocode-maps.yandex.ru/1.x/?format=json&geocode=#{addr}"
json = RestClient.get(http)
parced_json = ActiveSupport::JSON.decode(json)
coordinates = parced_json["response"]["GeoObjectCollection"]["featureMember"][0]["GeoObject"]["Point"]["pos"]
rescue NoMethodError
coordinates = nil
self.errors.add(:coordinates)
end
coordinates
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question