Class: Configatron::Proc

Inherits:
Object show all
Defined in:
lib/configatron/proc.rb

Overview

This class can be used to give special powers to a Configatron setting. See Configatron::Delayed and Configatron::Dynamic as examples of how this works.

This class can be subclassed easily. The key is to override the finalize? method.

Example:

class RunThreeTimes < Configatron::Proc
  def finalize?
    self.execution_count == 3
  end
end

configatron.some.rand.generator = RunThreeTimes.new do
  rand
end

configatron.some.rand.generator # => 0.169280668547299
configatron.some.rand.generator # => 0.298880544243205
configatron.some.rand.generator # => 0.421091617110779
configatron.some.rand.generator # => 0.421091617110779
configatron.some.rand.generator # => 0.421091617110779

Direct Known Subclasses

Delayed, Dynamic

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Proc

Requires a block to be passed into it.



33
34
35
36
# File 'lib/configatron/proc.rb', line 33

def initialize(&block)
  self.execution_count = 0
  self.block = block
end

Instance Attribute Details

#blockObject

The block that you want executed when you call the execute method.



30
31
32
# File 'lib/configatron/proc.rb', line 30

def block
  @block
end

#execution_countObject

The number of times this Proc has been executed



28
29
30
# File 'lib/configatron/proc.rb', line 28

def execution_count
  @execution_count
end

Instance Method Details

#executeObject

Executes the block attribute, ticks up the execution_count attribute by one and then returns the value of the executed block



41
42
43
44
45
# File 'lib/configatron/proc.rb', line 41

def execute
  val = self.block.call
  self.execution_count += 1
  return val
end

#finalize?Boolean

Returns true if Configatron should cache the results of the execute method, thereby never calling it again.

Returns:

  • (Boolean)


50
51
52
# File 'lib/configatron/proc.rb', line 50

def finalize?
  self.execution_count == 1
end