Created
November 22, 2012 02:29
-
-
Save mildmojo/4129123 to your computer and use it in GitHub Desktop.
ARel named function helpers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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