Sha256: 99a55b15b78904a0f850db748047416250081ef01f0963a5ea421f1c150adaf3

Contents?: true

Size: 946 Bytes

Versions: 2

Compression:

Stored size: 946 Bytes

Contents

module Nanoc::Int
  # Holds a value that might be generated lazily.
  #
  # @api private
  class LazyValue
    # @param [Object, Proc] value_or_proc A value or a proc to generate the value
    def initialize(value_or_proc)
      @value = { raw: value_or_proc }
    end

    # @return [Object] The value, generated when needed
    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

    # Returns a new lazy value that will apply the given transformation when the value is requested.
    #
    # @yield resolved value
    #
    # @return [Nanoc::Int::LazyValue]
    def map
      Nanoc::Int::LazyValue.new(-> { yield(value) })
    end

    # @return [void]
    def freeze
      super
      @value.__nanoc_freeze_recursively unless @value[:raw]
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
nanoc-4.2.0 lib/nanoc/base/entities/lazy_value.rb
nanoc-4.2.0b1 lib/nanoc/base/entities/lazy_value.rb