Class: Nanoc::Core::LazyValue

Inherits:
Object
  • Object
show all
Includes:
ContractsSupport
Defined in:
lib/nanoc/core/lazy_value.rb

Overview

Holds a value that might be generated lazily.

Instance Method Summary collapse

Methods included from ContractsSupport

enabled?, included, setup_once, warn_about_performance

Constructor Details

#initialize(value_or_proc) ⇒ LazyValue

Takes a value or a proc to generate the value



10
11
12
# File 'lib/nanoc/core/lazy_value.rb', line 10

def initialize(value_or_proc)
  @value = { raw: value_or_proc }
end

Instance Method Details

#freezeObject



31
32
33
34
35
# File 'lib/nanoc/core/lazy_value.rb', line 31

def freeze
  super
  @value.__nanoc_freeze_recursively unless @value[:raw]
  self
end

#mapObject

Returns a new lazy value that will apply the given transformation when the value is requested.



26
27
28
# File 'lib/nanoc/core/lazy_value.rb', line 26

def map
  self.class.new(-> { yield(value) })
end

#valueObject

Returns the value, generated when needed



15
16
17
18
19
20
21
22
# File 'lib/nanoc/core/lazy_value.rb', line 15

def value
  if @value.key?(:raw)
    value = @value.delete(:raw)
    @value[:final] = value.respond_to?(:call) ? value.call : value
    @value.__nanoc_freeze_recursively if frozen?
  end
  @value[:final]
end