Class: SpatialProximity

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/spatial_proximity.rb

Class Method Summary collapse

Class Method Details

.between(scope1, scope2) ⇒ Object



5
6
7
8
9
# File 'app/models/spatial_proximity.rb', line 5

def self.between(scope1, scope2)
  where condition_sql(scope1, scope2, <<~SQL.squish)
    (#{SpatialFeatures::Utils.polymorphic_condition(scope1, 'model_a')} AND #{SpatialFeatures::Utils.polymorphic_condition(scope2, 'model_b')})
  SQL
end

.condition_sql(scope1, scope2, template, pattern_a = 'model_a', pattern_b = 'model_b') ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'app/models/spatial_proximity.rb', line 11

def self.condition_sql(scope1, scope2, template, pattern_a = 'model_a', pattern_b = 'model_b')
  scope1_type = SpatialFeatures::Utils.base_class_of(scope1).to_s
  scope2_type = SpatialFeatures::Utils.base_class_of(scope2).to_s

  if scope1_type < scope2_type
    template
  elsif scope1_type > scope2_type
    template.gsub(pattern_a, 'model_c').gsub(pattern_b, pattern_a).gsub('model_c', pattern_b)
  else
    <<~SQL.squish
      (#{template}) OR (#{template.gsub(pattern_a, 'model_c').gsub(pattern_b, pattern_a).gsub('model_c', pattern_b)})
    SQL
  end
end

.normalizeObject

Ensure the ‘earliest’ model is always model a



27
28
29
30
# File 'app/models/spatial_proximity.rb', line 27

def self.normalize
  unnormalized
    .update_all('model_a_type = model_b_type, model_b_type = model_a_type, model_a_id = model_b_id, model_b_id = model_a_id')
end

.unnormalizedObject



32
33
34
# File 'app/models/spatial_proximity.rb', line 32

def self.unnormalized
  where('model_a_type > model_b_type OR (model_a_type = model_b_type AND model_a_id > model_b_id)')
end