Module: DirtyMemoize
- Defined in:
- lib/dirty-memoize.rb
Overview
Like Memoize, but designed for mutable and parametizable objects
Use when:
-
You have one expensive method (#compute) which set many internal variables. So, is preferable lazy evaluation of these dependent variables.
-
The expensive operation depends on one or more parameters
-
Changes on one or more parameters affect all dependent variables
-
You may want to hide the call of ‘compute’ operation
-
The user could want test several different parameters values
By default, the method to compute should be called #compute. Set constant DIRTY_COMPUTE to the name of other method if you need it
Example:
class ExpensiveCalculation
extend DirtyMemoize
attr_accessor :y, :z
def initialize(y=nil,z=nil)
@y=y
@z=z
def compute
@a=@y*1000+@z*1000
end
def a
@a.nil? nil : "This is the value: #{@a}"
end
end
puts ExpensiveCalculation.new(1,2).a
Defined Under Namespace
Modules: ClassMethods
Constant Summary collapse
- VERSION =
"0.0.4"
Class Method Summary collapse
Instance Method Summary collapse
- #clean_cache ⇒ Object
-
#compute_count ⇒ Object
Number of compute’s runs.
-
#dirty? ⇒ Boolean
Is the object dirty?.
Class Method Details
.included(receiver) ⇒ Object
Trick from github.com/ecomba/memoizable
34 35 36 |
# File 'lib/dirty-memoize.rb', line 34 def self.included(receiver) #:nodoc: receiver.extend DirtyMemoize::ClassMethods end |
Instance Method Details
#clean_cache ⇒ Object
80 81 82 83 |
# File 'lib/dirty-memoize.rb', line 80 def clean_cache @cache=Hash.new @dirty=:true end |
#compute_count ⇒ Object
Number of compute’s runs
77 78 79 |
# File 'lib/dirty-memoize.rb', line 77 def compute_count @compute_count||=0 end |
#dirty? ⇒ Boolean
Is the object dirty?
72 73 74 75 |
# File 'lib/dirty-memoize.rb', line 72 def dirty? @dirty||=:true @dirty==:true end |