Module: CachedValues

Defined in:
lib/cached_values.rb

Overview

:nodoc:

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.perform_save?Boolean

Returns:

  • (Boolean)


5
6
7
# File 'lib/cached_values.rb', line 5

def self.perform_save?
  @perform_save ||= true
end

.without_saving_recordObject



9
10
11
12
13
# File 'lib/cached_values.rb', line 9

def self.without_saving_record
  @perform_save = false
  yield
  @perform_save = true
end

Instance Method Details

#caches_value(name, options = {}) ⇒ Object

USAGE:

a very simple case in which cached_values works just like the .count method on a has_many association:

class Company < ActiveRecord::Base
  caches_value :total_employees, :sql => 'select count(*) from employees where company_id = #{id}'
end

a more sophisticated example:

class User < ActiveRecord::Base
  has_many :trinkets
  has_many :sales, :through => :trinkets
  caches_value :remaining_trinket_sales_allotted, :sql => '... very complicated sql here ...'
end

user = User.find(:first)
user.remaining_trinket_sales_allotted # => 70
Trinket.delete_all # <= any operation that would affect our value
user.remaining_trinket_sales_allotted # => 70
user.remaining_trinket_sales_allotted.reload # => 113

You can also calculate the value in Ruby. This can be done by a string to be eval’ed or a Proc. Both are evaluated in the context of the record instance.

class User < ActiveRecord::Base
  caches_value :expensive_calculation, :eval => "some_big_expensize_calculation(self.id)"
  caches_value :other_expensive_process, :eval => Proc.new {|record| record.other_expensize_process }
end


46
47
48
49
50
51
52
53
54
55
# File 'lib/cached_values.rb', line 46

def caches_value(name, options = {})
  reflection = create_cached_value_reflection(name, options)

  configure_dependency_for_cached_value(reflection)

  reflection.options[:cache] ||= reflection.name unless false == options[:cache]

  cached_value_accessor_method(reflection, ActiveRecord::CachedValue)
  cached_value_callback_methods(reflection)
end