Skip to content

Commit

Permalink
Add :select_bearing option for near scope.
Browse files Browse the repository at this point in the history
Should close #374.
  • Loading branch information
nicolasdespres committed Jan 14, 2013
1 parent 4db0f53 commit 81ae5d4
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
11 changes: 8 additions & 3 deletions lib/geocoder/stores/active_record.rb
Expand Up @@ -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. <formula> 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)
Expand All @@ -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)

Expand All @@ -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"
}
Expand Down Expand Up @@ -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

##
Expand Down
8 changes: 8 additions & 0 deletions test/near_test.rb
Expand Up @@ -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)
Expand Down

0 comments on commit 81ae5d4

Please sign in to comment.