Module: CachedValues
- Defined in:
- lib/cached_values.rb
Overview
:nodoc:
Class Method Summary collapse
- .disable! ⇒ Object
- .enable! ⇒ Object
- .perform_save? ⇒ Boolean
- .run? ⇒ Boolean
- .without_saving_record ⇒ Object
Instance Method Summary collapse
-
#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 => ‘…
Class Method Details
.disable! ⇒ Object
20 21 22 |
# File 'lib/cached_values.rb', line 20 def self.disable! @enabled = false end |
.enable! ⇒ Object
24 25 26 |
# File 'lib/cached_values.rb', line 24 def self.enable! @enabled = true end |
.perform_save? ⇒ Boolean
5 6 7 |
# File 'lib/cached_values.rb', line 5 def self.perform_save? @perform_save ||= true end |
.run? ⇒ Boolean
15 16 17 18 |
# File 'lib/cached_values.rb', line 15 def self.run? @enabled = true if @enabled.nil? @enabled end |
.without_saving_record ⇒ Object
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
59 60 61 62 63 64 65 66 67 68 |
# File 'lib/cached_values.rb', line 59 def caches_value(name, = {}) reflection = create_cached_value_reflection(name, ) configure_dependency_for_cached_value(reflection) reflection.[:cache] ||= reflection.name unless false == [:cache] cached_value_accessor_method(reflection, ActiveRecord::CachedValue) cached_value_callback_methods(reflection) end |