class Nanoc::Helpers::Capturing::SetContent

@api private

Public Class Methods

new(name, params, item) click to toggle source
# File lib/nanoc/helpers/capturing.rb, line 10
def initialize(name, params, item)
  @name = name
  @params = params
  @item = item
end

Public Instance Methods

run(&) click to toggle source
# File lib/nanoc/helpers/capturing.rb, line 16
def run(&)
  existing_behavior = @params.fetch(:existing, :error)

  # Capture
  content_string = capture(&)

  # Get existing contents and prep for store
  compiled_content_store = @item._context.compiled_content_store
  rep = @item.reps[:default]._unwrap
  capture_name = :"__capture_#{@name}"
  old_content_string =
    case existing_behavior
    when :overwrite
      ''
    when :append
      c = compiled_content_store.get(rep, capture_name)
      c ? c.string : ''
    when :error
      contents = compiled_content_store.get(rep, capture_name)
      if contents && contents.string != content_string
        # FIXME: get proper exception
        raise "a capture named #{@name.inspect} for #{@item.identifier} already exists"
      else
        ''
      end
    else
      raise ArgumentError, 'expected :existing_behavior param to #content_for to be one of ' \
        ":overwrite, :append, or :error, but #{existing_behavior.inspect} was given"
    end

  # Store
  new_content = Nanoc::Core::TextualContent.new(old_content_string + content_string)
  compiled_content_store.set(rep, capture_name, new_content)
end