Module: LooseTightDictionary::CachedResult::ActiveRecordBaseExtension

Defined in:
lib/loose_tight_dictionary/cached_result.rb

Instance Method Summary collapse

Instance Method Details

#cache_loose_tight_dictionary_matches_with(other_active_record_class, options) ⇒ Object

required options: :primary_key - what to call on this class :foreign_key - what to call on the other class



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/loose_tight_dictionary/cached_result.rb', line 27

def cache_loose_tight_dictionary_matches_with(other_active_record_class, options)
  other = other_active_record_class.to_s.singularize.camelcase
  me = name
  if me < other
    a = me
    b = other
    primary_key = :a
    foreign_key = :b
  else
    a = other
    b = me
    primary_key = :b
    foreign_key = :a
  end

  # def aircraft
  define_method other.underscore.pluralize do
    other.constantize.where options[:foreign_key] => send("#{other.underscore.pluralize}_foreign_keys")
  end
  
  # def flight_segments_foreign_keys
  define_method "#{other.underscore.pluralize}_foreign_keys" do
    fz = ::LooseTightDictionary::CachedResult.arel_table
    sql = fz.project(fz[foreign_key]).where(fz["#{primary_key}_class".to_sym].eq(self.class.name).and(fz["#{foreign_key}_class".to_sym].eq(other)).and(fz[primary_key].eq(send(options[:primary_key])))).to_sql
    connection.select_values sql
  end
  
  # def cache_aircraft!
  define_method "cache_#{other.underscore.pluralize}!" do
    other_class = other.constantize
    primary_key_value = send options[:primary_key]
    other_class.loose_tight_dictionary.find_all(primary_key_value).each do |other_instance|
      attrs = {}
      attrs[primary_key] = primary_key_value
      attrs["#{primary_key}_class"] = self.class.name
      attrs[foreign_key] = other_instance.send options[:foreign_key]
      attrs["#{foreign_key}_class"] = other
      unless ::LooseTightDictionary::CachedResult.exists? attrs
        ::LooseTightDictionary::CachedResult.create! attrs
      end
    end
  end
end