Skip to content

Instantly share code, notes, and snippets.

@billeisenhauer
Created November 13, 2008 02:52
Show Gist options
  • Save billeisenhauer/24346 to your computer and use it in GitHub Desktop.
Save billeisenhauer/24346 to your computer and use it in GitHub Desktop.
# Class singleton methods to mix into ActiveRecord.
module SingletonMethods # :nodoc:
# Extends the existing find method in potentially two ways:
# - If a mappable instance exists in the options, adds a distance column.
# - If a mappable instance exists in the options and the distance column exists in the
# conditions, substitutes the distance sql for the distance column -- this saves
# having to write the gory SQL.
def find(*args)
options = extract_options_from_args!(args)
origin = extract_origin_from_options(options)
units = extract_units_from_options(options)
formula = extract_formula_from_options(options)
add_distance_to_select(options, origin, units, formula) if origin
apply_find_scope(args, options)
apply_distance_scope(options)
substitute_distance_in_conditions(options, origin, units, formula) if origin && options.has_key?(:conditions)
args.push(options)
super(*args)
end
# Finds within a distance radius.
def find_within(distance, options={})
options[:within] = distance
find(:all, options)
end
alias find_inside find_within
# Finds beyond a distance radius.
def find_beyond(distance, options={})
options[:beyond] = distance
find(:all, options)
end
alias find_outside find_beyond
# Finds according to a range. Accepts inclusive or exclusive ranges.
def find_by_range(range, options={})
options[:range] = range
find(:all, options)
end
# Finds the closest to the origin.
def find_closest(options={})
find(:nearest, options)
end
alias find_nearest find_closest
# Finds the farthest from the origin.
def find_farthest(options={})
find(:farthest, options)
end
# Returns the distance calculation to be used as a display column or a condition. This
# is provide for anyone wanting access to the raw SQL.
def distance_sql(origin, units=default_units, formula=default_formula)
case formula
when :sphere
sql = sphere_distance_sql(origin, units)
when :flat
sql = flat_distance_sql(origin, units)
end
sql
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment