Module: NutritionCalculator::CachedOutputsWithRecalculation

Included in:
CalorieBudgeter
Defined in:
lib/nutrition_calculator/cached_outputs_with_recalculation.rb

Overview

Define an object that turns inputs into outputs. With Caching! And Logging!

Examples:

class Foo
  extend NutritionCalculator::CachedOutputsWithRecalculation

  def_input :bar

  def_input :spam, validate_with: ->(value) {
    value != 'ham'
  }

  def_output :baz do
    bar.expensive_operation
  end
end

x = Foo.new

x.baz
#=> Raises a RuntimeError because input bar was not set

x.spam = 'ham'
#=> Raises a
  NutritionCalculator::CachedOutputsWithRecalculation::InvalidInputError
  because the validation returned false.

a_thing = ExpensiveObject.new

x.bar = a_thing
x.baz
#=> result of `a_thing.expensive_operation`

# `a_thing.expensive_operation` will not be called again
x.baz
#=> cached result of `a_thing.expensive_operation`

# `a_thing.expensive_operation` will be called again since input is
# reassigned
x.bar = a_thing
x.baz
#=> result of `a_thing.expensive_operation`

Defined Under Namespace

Classes: InvalidInputError

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(other) ⇒ Object



52
53
54
# File 'lib/nutrition_calculator/cached_outputs_with_recalculation.rb', line 52

def self.extended(other)
  other.include(InstanceMethods)
end

Instance Method Details

#def_input(name, validate_with: ->(_) { true }) ⇒ Object

Defines accessors for the named attribute

Assignment to the named accessor will cause all cached results to be recalculated the next time they are called.

Parameters:

  • name (Symbol)


62
63
64
65
# File 'lib/nutrition_calculator/cached_outputs_with_recalculation.rb', line 62

def def_input(name, validate_with: ->(_) { true })
  def_input_writer name, validator: validate_with
  def_input_reader name
end

#def_output(name, &block) ⇒ Object

Defines attribute reader methods for the specified calculation

The result of the block is cached as long as no inputs are re-assigned after the attribute reader is called. Additionaly, if ‘#logger` is set, the result of the calculation will be sent to the DEBUG log when the block is run.

Parameters:

  • name (Symbol)
  • block (Proc)

    will be ‘instance_eval`ed in the Object as though it were the body of a regular method



77
78
79
80
81
# File 'lib/nutrition_calculator/cached_outputs_with_recalculation.rb', line 77

def def_output(name, &block)
  define_method(name) do
    cache_and_debug(name, &block)
  end
end