From 81ae5d4e4d3d93e697760211faa7a3f4fa1eb2fb Mon Sep 17 00:00:00 2001 From: Nicolas Despres Date: Mon, 14 Jan 2013 10:55:57 +0100 Subject: [PATCH] Add :select_bearing option for near scope. Should close #374. --- lib/geocoder/stores/active_record.rb | 11 ++++++++--- test/near_test.rb | 8 ++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/lib/geocoder/stores/active_record.rb b/lib/geocoder/stores/active_record.rb index 3d8af3939..9255a4cb0 100644 --- a/lib/geocoder/stores/active_record.rb +++ b/lib/geocoder/stores/active_record.rb @@ -97,6 +97,7 @@ def distance_from_sql(location, *args) # * +:select+ - string with the SELECT SQL fragment (e.g. “id, name”) # * +:select_distance+ - whether to include the distance alias in the # SELECT SQL fragment (e.g. AS distance) + # * +:select_bearing+ - like +:select_distance+ but for bearing. # * +:order+ - column(s) for ORDER BY SQL clause; default is distance; # set to false or nil to omit the ORDER BY clause # * +:exclude+ - an object to exclude (used by the +nearbys+ method) @@ -105,6 +106,7 @@ def near_scope_options(latitude, longitude, radius = 20, options = {}) options[:units] ||= (geocoder_options[:units] || Geocoder.config.units) select_distance = options.fetch(:select_distance, true) options[:order] = "" if !select_distance && !options.include?(:order) + select_bearing = options.fetch(:select_bearing, true) bearing = bearing_sql(latitude, longitude, options) distance = distance_sql(latitude, longitude, options) @@ -123,7 +125,7 @@ def near_scope_options(latitude, longitude, radius = 20, options = {}) { :select => select_clause(options[:select], select_distance ? distance : nil, - bearing), + select_bearing ? bearing : nil), :conditions => add_exclude_condition(conditions, options[:exclude]), :order => options.include?(:order) ? options[:order] : "distance ASC" } @@ -179,8 +181,11 @@ def select_clause(columns, distance = nil, bearing = nil) clause += ", " unless clause.empty? clause += "#{distance} AS distance" end - clause + - (bearing ? ", #{bearing} AS bearing" : "") + if bearing + clause += ", " unless clause.empty? + clause += "#{bearing} AS bearing" + end + clause end ## diff --git a/test/near_test.rb b/test/near_test.rb index 9bd6a88ca..05411dd55 100644 --- a/test/near_test.rb +++ b/test/near_test.rb @@ -27,6 +27,14 @@ def test_near_scope_options_with_no_distance assert_no_consecutive_comma(result[:select]) end + def test_near_scope_options_with_no_bearing + result = Event.send(:near_scope_options, 1.0, 2.0, 5, :select_bearing => false) + + assert_match /AS distance/, result[:select] + assert_no_match /AS bearing/, result[:select] + assert_no_consecutive_comma(result[:select]) + end + private def assert_no_consecutive_comma(string)