module RailsRbs::Rules::Location

Used by the location default rule to ensure an object's observed field matches a set latitude and longitude for the rule. Assumes the rule supports a latitude and longitude method

Public Instance Methods

filter_objects(association) click to toggle source

Return an association of active record objects that match the latitude and longitude of the rule. This is done using the provided association as a base to query from. @param association Active record association, relation or collection proxy that supports the where interface.

# File lib/rails_rbs/rules/location.rb, line 30
def filter_objects(association)
  matching_lat, matching_long = self.latitude, self.longitude
  # Attempt to coerce the types if we can
  if self.respond_to?(:enforced_type) && self.respond_to?(:force_type)
    matching_lat, matching_long = force_type(matching_lat), force_type(matching_long)
  end
  association.where("latitude = ? AND longitude = ?", matching_lat, matching_long)
end
follows_rule?(*objects) click to toggle source

Check one or more object's observed_field to ensure it matches the rule's latitude and longitude values. This method assumes the provided object(s) observed_field will return an array of [latitude, longitude] @param objects [Array<ActiveRecord::Base>] active record objects, or objects that respond to the observed_field and return an array of [latitude, longitude] from it.

# File lib/rails_rbs/rules/location.rb, line 13
def follows_rule?(*objects)
  objects.all? do |object|
    # We expect the observed field to return an array of [latitude, longitude]
    source_lat, source_long   =  *object.send(self.observed_field.to_sym)
    dest_lat,   dest_long     =  *[self.latitude, self.longitude]
    # Attempt to coerce the types if we can
    if self.respond_to?(:enforced_type) && self.respond_to?(:force_type)
      [source_lat, source_long, dest_lat, dest_long].each { |val| force_type(val) }
    end
    # TODO: Use geocoding and distance of some sort here...
    source_lat == dest_lat && source_long == dest_long
  end
end