Module: DirtyMemoize

Defined in:
lib/dirty-memoize.rb

Overview

Like Memoize, but designed for mutable and parametizable objects

Use when:

  1. You have one expensive method (#compute) which set many internal variables. So, is preferable lazy evaluation of these dependent variables.

  2. The expensive operation depends on one or more parameters

  3. Changes on one or more parameters affect all dependent variables

  4. You may want to hide the call of ‘compute’ operation

  5. 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

Class Method Details

.included(receiver) ⇒ Object



34
35
36
# File 'lib/dirty-memoize.rb', line 34

def self.included(receiver) #:nodoc:
  receiver.extend DirtyMemoize::ClassMethods
end

Instance Method Details

#clean_cacheObject



80
81
82
83
# File 'lib/dirty-memoize.rb', line 80

def clean_cache
  @cache=Hash.new
  @dirty=:true
end

#compute_countObject

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?

Returns:

  • (Boolean)


72
73
74
75
# File 'lib/dirty-memoize.rb', line 72

def dirty?
  @dirty||=:true
  @dirty==:true
end