Module: Omen::Distance

Defined in:
lib/omen/distance.rb

Overview

The database function a reading measures a distance with. Created by the rake task rather than by a migration, for the reason Omen::TimeZone is: Rails' :ruby schema format dumps no functions, so db:schema:load would drop one a migration had made.

Constant Summary collapse

RADIUS =

The earth's mean radius in miles, which is what makes the answer miles.

3958.7613

Class Method Summary collapse

Class Method Details

.haversine(connection) ⇒ String

Declared over double precision, which numeric, real and integer all cast to implicitly, so a host's own column type does not have to be guessed at. Any argument NULL and the answer is NULL, the way a distance to nowhere ought to read.

Parameters:

  • connection (ActiveRecord::ConnectionAdapters::AbstractAdapter)

    a writing one.

Returns:

  • (String)

    the statement declaring the function.



19
20
21
22
23
24
25
# File 'lib/omen/distance.rb', line 19

def self.haversine(connection)
  "CREATE OR REPLACE FUNCTION #{name connection}(lat1 double precision, " \
    'lng1 double precision, lat2 double precision, lng2 double precision) ' \
    "RETURNS double precision AS $$ SELECT 2 * #{RADIUS} * asin(sqrt(" \
    'power(sin(radians(lat2 - lat1) / 2), 2) + cos(radians(lat1)) * cos(radians(lat2)) ' \
    '* power(sin(radians(lng2 - lng1) / 2), 2))) $$ LANGUAGE sql IMMUTABLE'
end

.name(connection) ⇒ String

Returns the function's name, quoted.

Parameters:

  • connection (ActiveRecord::ConnectionAdapters::AbstractAdapter)

    a writing one.

Returns:

  • (String)

    the function's name, quoted.



29
# File 'lib/omen/distance.rb', line 29

def self.name(connection) = connection.quote_table_name Omen::Instructions::MILES

.statements(connection) ⇒ Array<String>

DDL, which Active Record has no expression for, and not a query.

Parameters:

  • connection (ActiveRecord::ConnectionAdapters::AbstractAdapter)

    a writing one.

Returns:

  • (Array<String>)

    the statements to run, in order.



12
# File 'lib/omen/distance.rb', line 12

def self.statements(connection) = [ haversine(connection) ]