Module: Kasket::ReadMixin

Defined in:
lib/kasket/read_mixin.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



5
6
7
8
9
# File 'lib/kasket/read_mixin.rb', line 5

def self.extended(base)
  class << base
    alias_method_chain :find_by_sql, :kasket
  end
end

Instance Method Details

#find_by_sql_with_kasket(*args) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/kasket/read_mixin.rb', line 11

def find_by_sql_with_kasket(*args)
  sql = args[0]

  if use_kasket?
    if sql.respond_to?(:to_kasket_query)
      query = sql.to_kasket_query(self, args[1])
    else
      query = kasket_parser.parse(sanitize_sql(sql))
    end
  end

  if query && has_kasket_index_on?(query[:index])
    if query[:key].is_a?(Array)
      find_by_sql_with_kasket_on_id_array(query[:key])
    else
      if value = Kasket.cache.read(query[:key])
        if value.is_a?(Array)
          find_by_sql_with_kasket_on_id_array(value)
        else
          Array.wrap(value).collect { |record| instantiate(record.dup) }
        end
      else
        store_in_kasket(query[:key], find_by_sql_without_kasket(*args))
      end
    end
  else
    find_by_sql_without_kasket(*args)
  end
end

#find_by_sql_with_kasket_on_id_array(keys) ⇒ Object



41
42
43
44
45
46
47
48
49
# File 'lib/kasket/read_mixin.rb', line 41

def find_by_sql_with_kasket_on_id_array(keys)
  key_attributes_map = Kasket.cache.read_multi(*keys)

  found_keys, missing_keys = keys.partition{|k| key_attributes_map[k] }
  found_keys.each{|k| key_attributes_map[k] = instantiate(key_attributes_map[k].dup) }
  key_attributes_map.merge!(missing_records_from_db(missing_keys))

  key_attributes_map.values.compact
end