Skip to content

Instantly share code, notes, and snippets.

@mildmojo
Created November 22, 2012 02:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mildmojo/4129123 to your computer and use it in GitHub Desktop.
Save mildmojo/4129123 to your computer and use it in GitHub Desktop.
ARel named function helpers
# Collection of helpers for math-related ARel NamedFunctions.
#
# Include this in classes that need to do trig with DB functions. Lets you write
# cleaner code, like:
#
# dist = acos(sin(lat) * sin(arel_lat_field) +
# cos(lat) * cos(arel_lat_field) * cos(arel_lng_field)) * EARTH_RADIUS_KM
# band_num = round(dist / ring_width, 0)
# band_num.to_sql
# # => round(abs(acos(
# (sin(0.6639333703683045) *
# sin("places"."latitude" * 0.017453292519943295) +
# cos(0.6639333703683045) *
# cos("places"."latitude" * 0.017453292519943295) *
# cos("places"."longitude" * 0.017453292519943295))
# ) * 6371) / 10, 0)
#
module Arel
module Math
module Extras
FUNCTIONS = %w(cos sin acos round)
FUNCTIONS.each do |func|
define_method(func) do |*args|
Arel::Nodes::NamedFunction.new(func, args).extend(Arel::Math)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment