Class: ActiveRecord::Relation

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_cache/active_record.rb

Instance Method Summary collapse

Instance Method Details

#clear_smart_cacheObject



56
57
58
59
# File 'lib/simple_cache/active_record.rb', line 56

def clear_smart_cache
  cache_key = Digest::MD5.hexdigest(arel.to_sql)
  Rails.cache.write(cache_key, nil, :expires_in => 0.seconds)
end

#smart_cache(ttl = nil) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/simple_cache/active_record.rb', line 61

def smart_cache(ttl = nil)
  return @records if loaded?
  cache_key = Digest::MD5.hexdigest(arel.to_sql)
  results = Rails.cache.read(cache_key)
  return results if results
  @records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel.to_sql)

  preload = @preload_values
  preload +=  @includes_values unless eager_loading?
  preload.each {|associations| @klass.send(:preload_associations, @records, associations) }

  # @readonly_value is true only if set explicitly. @implicit_readonly is true if there
  # are JOINS and no explicit SELECT.
  readonly = @readonly_value.nil? ? @implicit_readonly : @readonly_value
  @records.each { |record| record.readonly! } if readonly

  @loaded = true
  # key_list = Rails.cache.read("short_cache_#{@klass.name}")
  # key_list = [] if key_list.nil?
  # key_list.push cache_key
  # Rails.cache.write("short_cache_#{@klass.name}", key_list)
  Rails.cache.write(cache_key, @records, :expires_in => eval("ttl || #{@klass.name}::EXPIRE_TIME"))
  @records
end