From 8c3827d05543f3a0dfbc8d926333e14e2b4d4350 Mon Sep 17 00:00:00 2001 From: Bonias <piotr@prograils.com> Date: Mon, 23 Dec 2013 23:21:49 +0100 Subject: [PATCH] lookup option for ActiveRecord::Base.geocoded_by can be a proc Example: class City < ActiveRecord::Base geocoded_by :address, :lookup => lambda{|obj| obj.custom_lookup } def custom_lookup # return custom lookup for record end end --- lib/geocoder/stores/base.rb | 8 +++++++- test/geocoder_test.rb | 6 ++++++ test/test_helper.rb | 21 +++++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/lib/geocoder/stores/base.rb b/lib/geocoder/stores/base.rb index f693130a..fd3ccaee 100644 --- a/lib/geocoder/stores/base.rb +++ b/lib/geocoder/stores/base.rb @@ -101,7 +101,13 @@ module Geocoder return end - query_options = [:lookup, :ip_lookup].inject({}){|hash, key| hash[key] = options[key] if options.has_key?(key); hash } + query_options = [:lookup, :ip_lookup].inject({}) do |hash, key| + if options.has_key?(key) + val = options[key] + hash[key] = val.respond_to?(:call) ? val.call(self) : val + end + hash + end results = Geocoder.search(query, query_options) # execute custom block, if specified in configuration diff --git a/test/geocoder_test.rb b/test/geocoder_test.rb index 2bd58a7a..34377782 100644 --- a/test/geocoder_test.rb +++ b/test/geocoder_test.rb @@ -63,6 +63,12 @@ class GeocoderTest < Test::Unit::TestCase assert_equal Geocoder::Result::Nominatim, v.result_class end + def test_geocode_with_custom_lookup_proc_param + v = BigChurch.new(*venue_params(:msg)) + v.geocode + assert_equal Geocoder::Result::Nominatim, v.result_class + end + def test_reverse_geocode_with_custom_lookup_param v = Temple.new(*landmark_params(:msg)) v.reverse_geocode diff --git a/test/test_helper.rb b/test/test_helper.rb index 78d5c6a5..61e6844b 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -268,6 +268,27 @@ class Church < ActiveRecord::Base end end +## +# Geocoded model with custom lookup as proc. +# +class BigChurch < ActiveRecord::Base + geocoded_by :address, :lookup => lambda{|obj| obj.custom_lookup } do |obj,results| + if result = results.first + obj.result_class = result.class + end + end + + def custom_lookup + :nominatim + end + + def initialize(name, address) + super() + write_attribute :name, name + write_attribute :address, address + end +end + ## # Reverse geocoded model with custom lookup. # -- GitLab