Module: RecordCache::Strategy::Util

Defined in:
lib/record_cache/strategy/util.rb

Defined Under Namespace

Modules: Collator

Constant Summary collapse

CLASS_KEY =
:c
ATTRIBUTES_KEY =
:a

Class Method Summary collapse

Class Method Details

.deserialize(serialized) ⇒ Object

deserialize a cached record



18
19
20
21
22
23
24
25
26
# File 'lib/record_cache/strategy/util.rb', line 18

def deserialize(serialized)
  record = serialized[CLASS_KEY].constantize.new
  attributes = serialized[ATTRIBUTES_KEY]
  record.instance_variable_set(:@attributes, Hash[attributes])
  record.instance_variable_set(:@new_record, false)
  record.instance_variable_set(:@changed_attributes, {})
  record.instance_variable_set(:@previously_changed, {})
  record
end

.filter!(records, wheres) ⇒ Object

Filter the cached records in memory only simple x = y or x IN (a,b,c) can be handled Example:

RecordCache::Strategy::Util.filter!(Apple.all, :price => [0.49, 0.59, 0.69], :name => "Green Apple")


32
33
34
35
36
37
38
39
40
41
# File 'lib/record_cache/strategy/util.rb', line 32

def filter!(records, wheres)
  wheres.each_pair do |attr, value|
    attr = attr.to_sym
    if value.is_a?(Array)
      records.reject! { |record| !value.include?(record.send(attr)) }
    else
      records.reject! { |record| record.send(attr) != value }
    end
  end
end

.serialize(record) ⇒ Object

serialize one record before adding it to the cache creates a shallow clone with a version and without associations



12
13
14
15
# File 'lib/record_cache/strategy/util.rb', line 12

def serialize(record)
  {CLASS_KEY => record.class.name,
   ATTRIBUTES_KEY => record.instance_variable_get(:@attributes)}.freeze
end

.sort!(records, *sort_orders) ⇒ Object

Sort the cached records in memory, similar to MySql sorting rules including collatiom Simply provide the Symbols of the attributes to sort in Ascending order, or use

<attribute>, false

for Descending order.

Example:

RecordCache::Strategy::Util.sort!(Apple.all, :name)
RecordCache::Strategy::Util.sort!(Apple.all, [:name, false])
RecordCache::Strategy::Util.sort!(Apple.all, [:price, false], :name)
RecordCache::Strategy::Util.sort!(Apple.all, [:price, false], [:name, true])
RecordCache::Strategy::Util.sort!(Apple.all, [[:price, false], [:name, true]])


52
53
54
55
56
57
58
59
60
61
62
# File 'lib/record_cache/strategy/util.rb', line 52

def sort!(records, *sort_orders)
  return records if records.empty? || sort_orders.empty?
  if sort_orders.first.is_a?(Array) && sort_orders.first.first.is_a?(Array)
    sort_orders = sort_orders.first
  else
    sort_orders = sort_orders.map{ |order| order.is_a?(Array) ? order : [order, true] } unless sort_orders.all?{ |order| order.is_a?(Array) }
  end
  records.sort!(&sort_proc(records.first.class, sort_orders))
  Collator.clear
  records
end