Class: Nanoc3::ItemRep

### Home Classes Methods

### In Files

- lib/nanoc3/base/item_rep.rb

### Parent

Object

### Methods

- ::new
- #assigns
- #compiled_content
- #content_at_snapshot
- #diff
- #filter
- #forget_progress
- #inspect
- #layout
- #outdated?
- #outdatedness_reason
- #snapshot
- #write

### Files

- ChangeLog
- LICENSE

### Class/Module Index

Quicksearch

- Nanoc3
- Nanoc3::ArrayExtensions
- Nanoc3::CLI
- Nanoc3::CLI::Base
- Nanoc3::CLI::Commands
- Nanoc3::CLI::Commands::Autocompile
- Nanoc3::CLI::Commands::Compile
- Nanoc3::CLI::Commands::CreateItem
- Nanoc3::CLI::Commands::CreateLayout
- Nanoc3::CLI::Commands::CreateSite
- Nanoc3::CLI::Commands::Debug
- Nanoc3::CLI::Commands::Help
- Nanoc3::CLI::Commands::Info
- Nanoc3::CLI::Commands::Update
- Nanoc3::CLI::Commands::View
- Nanoc3::CLI::Logger
- Nanoc3::CodeSnippet
- Nanoc3::Compiler
- Nanoc3::CompilerDSL
- Nanoc3::Context
- Nanoc3::DataSource
- Nanoc3::DataSources
- Nanoc3::DataSources::Delicious
- Nanoc3::DataSources::Filesystem
- Nanoc3::DataSources::FilesystemCombined
- Nanoc3::DataSources::FilesystemCompact
- Nanoc3::DataSources::FilesystemUnified
- Nanoc3::DataSources::FilesystemVerbose
- Nanoc3::DataSources::LastFM
- Nanoc3::DataSources::Twitter
- Nanoc3::DependencyTracker
- Nanoc3::DirectedGraph
- Nanoc3::Errors
- Nanoc3::Errors::CannotDetermineFilter
- Nanoc3::Errors::CannotLayoutBinaryItem
- Nanoc3::Errors::CannotUseBinaryFilter
- Nanoc3::Errors::CannotUseTextualFilter
- Nanoc3::Errors::DataNotYetAvailable
- Nanoc3::Errors::Generic
- Nanoc3::Errors::NoMatchingCompilationRuleFound
- Nanoc3::Errors::NoMatchingRoutingRuleFound
- Nanoc3::Errors::NoRulesFileFound
- Nanoc3::Errors::RecursiveCompilation
- Nanoc3::Errors::UnknownDataSource
- Nanoc3::Errors::UnknownFilter
- Nanoc3::Errors::UnknownLayout
- Nanoc3::Errors::UnmetDependency
- Nanoc3::Extra
- Nanoc3::Extra::AutoCompiler
- Nanoc3::Extra::CHiCk
- Nanoc3::Extra::CHiCk::CacheController
- Nanoc3::Extra::CHiCk::Client
- Nanoc3::Extra::CHiCk::RackClient
- Nanoc3::Extra::Context
- Nanoc3::Extra::Deployers
- Nanoc3::Extra::Deployers::Rsync
- Nanoc3::Extra::FileProxy
- Nanoc3::Extra::TimeExtensions
- Nanoc3::Extra::VCS
- Nanoc3::Extra::VCSes
- Nanoc3::Extra::VCSes::Bazaar
- Nanoc3::Extra::VCSes::Dummy
- Nanoc3::Extra::VCSes::Git
- Nanoc3::Extra::VCSes::Mercurial
- Nanoc3::Extra::VCSes::Subversion
- Nanoc3::Extra::Validators
- Nanoc3::Extra::Validators::Links
- Nanoc3::Extra::Validators::Links::EachPairEnumerator
- Nanoc3::Extra::Validators::W3C
- Nanoc3::Filter
- Nanoc3::Filters
- Nanoc3::Filters::BlueCloth
- Nanoc3::Filters::CodeRay
- Nanoc3::Filters::ColorizeSyntax
- Nanoc3::Filters::ERB
- Nanoc3::Filters::Erubis
- Nanoc3::Filters::Haml
- Nanoc3::Filters::Kramdown
- Nanoc3::Filters::Less
- Nanoc3::Filters::Markaby
- Nanoc3::Filters::Maruku
- Nanoc3::Filters::RDiscount
- Nanoc3::Filters::RDoc
- Nanoc3::Filters::Rainpress
- Nanoc3::Filters::RedCloth
- Nanoc3::Filters::RelativizePaths
- Nanoc3::Filters::RubyPants
- Nanoc3::Filters::Sass
- Nanoc3::HashExtensions
- Nanoc3::Helpers
- Nanoc3::Helpers::Blogging
- Nanoc3::Helpers::Breadcrumbs
- Nanoc3::Helpers::Capturing
- Nanoc3::Helpers::Filtering
- Nanoc3::Helpers::HTMLEscape
- Nanoc3::Helpers::LinkTo
- Nanoc3::Helpers::Rendering
- Nanoc3::Helpers::Tagging
- Nanoc3::Helpers::Text
- Nanoc3::Helpers::XMLSitemap
- Nanoc3::Item
- Nanoc3::ItemRep
- Nanoc3::Layout
- Nanoc3::NotificationCenter
- Nanoc3::PluginRegistry
- Nanoc3::PluginRegistry::PluginMethods
- Nanoc3::Rule
- Nanoc3::RuleContext
- Nanoc3::Site
- Nanoc3::StringExtensions
- Nanoc3::Tasks
- Nanoc3::Tasks::Clean
- Array
- Enumerable
- Hash
- Object
- OrderedHash
- String
- Time

No matching classes.

# Nanoc3::ItemRep

A single representation (rep) of an item ({Nanoc3::Item}). An item can have multiple representations. A representation has its own output file. A single item can therefore have multiple output files, each run through a different set of filters with a different layout.

An item representation is observable. The following events will be notified:

- `:compilation_started`

- `:compilation_ended`

- `:filtering_started`

- `:filtering_ended`

The compilation-related events have one parameters (the item representation); the filtering-related events have two (the item representation, and a symbol containing the filter class name).

### Constants

OUTDATEDNESS_REASON_DESCRIPTIONS

  The descriptive strings for each outdatedness reason. This hash is used by the {outdatedness_reason} method.

### Attributes

binary[R]

@return [Boolean] true if this rep is currently binary; false otherwise

binary?[R]

@return [Boolean] true if this rep is currently binary; false otherwise

compiled[RW]

@return [Boolean] true if this representation has already been compiled during the current or last compilation session; false otherwise

compiled?[RW]

@return [Boolean] true if this representation has already been compiled during the current or last compilation session; false otherwise

created[RW]

@return [Boolean] true if this rep’s output file was created during the current or last compilation session; false otherwise

created?[RW]

@return [Boolean] true if this rep’s output file was created during the current or last compilation session; false otherwise

force_outdated[RW]

@return [Boolean] true if this rep is forced to be dirty (e.g. because of the `–force` commandline option); false otherwise

item[R]

@return [Nanoc3::Item] The item to which this rep belongs

modified[RW]

@return [Boolean] true if this rep’s output file has changed since the last time it was compiled; false otherwise

modified?[RW]

@return [Boolean] true if this rep’s output file has changed since the last time it was compiled; false otherwise

name[R]

@return [Symbol] The representation’s unique name

path[RW]

@return [String] The item rep’s path, as used when being linked to. It starts with a slash and it is relative to the output directory. It does not include the path to the output directory. It will not include the filename if the filename is an index filename.

raw_path[RW]

@return [String] The item rep’s raw path. It is relative to the current working directory and includes the path to the output directory. It also includes the filename, even if it is an index filename.

written[R]

@return [Boolean] true if this representation’s compiled content has been written during the current or last compilation session; false otherwise

written?[R]

@return [Boolean] true if this representation’s compiled content has been written during the current or last compilation session; false otherwise

### Public Class Methods

new(item, name) click to toggle source

Creates a new item representation for the given item.

@param [Nanoc3::Item] item The item to which the new representation will belong.

@param [Symbol] name The unique name for the new item representation.

    # File lib/nanoc3/base/item_rep.rb, line 88
    def initialize(item, name)
      # Set primary attributes
      @item   = item
      @name   = name

      # Set binary
      @binary = @item.binary?

      # Initialize content and filenames
      initialize_content
      @old_content = nil

      # Reset flags
      @compiled       = false
      @modified       = false
      @created        = false
      @written        = false
      @force_outdated = false
    end

### Public Instance Methods

assigns() click to toggle source

@return [Hash] The assignments that should be available when compiling the content.

    # File lib/nanoc3/base/item_rep.rb, line 178
    def assigns
      if self.binary?
        content_or_filename_assigns = { :filename => @filenames[:last] }
      else
        content_or_filename_assigns = { :content => @content[:last] }
      end

      content_or_filename_assigns.merge({
        :item       => self.item,
        :item_rep   => self,
        :items      => self.item.site.items,
        :layouts    => self.item.site.layouts,
        :config     => self.item.site.config,
        :site       => self.item.site
      })
    end

compiled_content(params={}) click to toggle source

Returns the compiled content from a given snapshot.

@option params [String] :snapshot The name of the snapshot from which to fetch the compiled content. By default, the returned compiled content will be the content compiled right before the first layout call (if any).

@return [String] The compiled content at the given snapshot (or the default snapshot if no snapshot is specified)

    # File lib/nanoc3/base/item_rep.rb, line 204
    def compiled_content(params={})
      # Notify
      Nanoc3::NotificationCenter.post(:visit_started, self.item)
      Nanoc3::NotificationCenter.post(:visit_ended,   self.item)

      # Debug
      puts "*** Attempting to fetch content for #{self.inspect}" if $DEBUG

      # Require compilation
      raise Nanoc3::Errors::UnmetDependency.new(self) unless compiled?

      # Get name of last pre-layout snapshot
      snapshot_name = params[:snapshot]
      if @content[:pre]
        snapshot_name ||= :pre
      else
        snapshot_name ||= :last
      end

      # Check presence of snapshot
      if @content[snapshot_name].nil?
        warn "WARNING: The “#{self.item.identifier}” item (rep “#{self.name}”) does not have the requested snapshot named #{snapshot_name.inspect}.\n\n* Make sure that you are requesting the correct snapshot.\n* It is not possible to request the compiled content of a binary item representation; if this item is marked as binary even though you believe it should be textual, you may need to add the extension of this item to the site configuration’s `text_extensions` array.".make_compatible_with_env
      end

      # Get content
      @content[snapshot_name]
    end

content_at_snapshot(snapshot=:pre) click to toggle source

@deprecated Use {Nanoc3::ItemRep#compiled_content} instead.

    # File lib/nanoc3/base/item_rep.rb, line 233
    def content_at_snapshot(snapshot=:pre)
      compiled_content(:snapshot => snapshot)
    end

diff() click to toggle source

Creates and returns a diff between the compiled content before the current compilation session and the content compiled in the current compilation session.

@return [String, nil] The difference between the old and new compiled content in `diff(1)` format, or nil if there is no previous compiled content

    # File lib/nanoc3/base/item_rep.rb, line 393
    def diff
      if self.binary?
        nil
      else
         @diff_thread.join if @diff_thread
        @diff
      end
    end

filter(filter_name, filter_args={}) click to toggle source

Runs the item content through the given filter with the given arguments. This method will replace the content of the `:last` snapshot with the filtered content of the last snapshot.

This method is supposed to be called only in a compilation rule block (see {Nanoc3::CompilerDSL#compile}).

@param [Symbol] filter_name The name of the filter to run the item representations’ content through

@param [Hash] filter_args The filter arguments that should be passed to the filter’s run method

@return [void]

    # File lib/nanoc3/base/item_rep.rb, line 260
    def filter(filter_name, filter_args={})
      # Get filter class
      klass = filter_named(filter_name)
      raise Nanoc3::Errors::UnknownFilter.new(filter_name) if klass.nil?

      # Check whether filter can be applied
      if klass.from_binary? && !self.binary?
        raise Nanoc3::Errors::CannotUseBinaryFilter.new(self, klass)
      elsif !klass.from_binary? && self.binary?
        raise Nanoc3::Errors::CannotUseTextualFilter.new(self, klass)
      end

      # Create filter
      filter = klass.new(assigns)

      # Run filter
      Nanoc3::NotificationCenter.post(:filtering_started, self, filter_name)
      source = self.binary? ? @filenames[:last] : @content[:last]
      result = filter.run(source, filter_args)
      if klass.to_binary?
        @filenames[:last] = filter.output_filename
      else
        @content[:last] = result
      end
      @binary = klass.to_binary?
      Nanoc3::NotificationCenter.post(:filtering_ended, self, filter_name)

      # Check whether file was written
      if self.binary? && !File.file?(filter.output_filename)
        raise RuntimeError,
          "The #{filter_name.inspect} filter did not write anything to the required output file, #{filter.output_filename}."
      end

      # Create snapshot
      snapshot(@content[:post] ? :post : :pre) unless self.binary?
    end

forget_progress() click to toggle source

Resets the compilation progress for this item representation. This is necessary when an unmet dependency is detected during compilation. This method should probably not be called directly.

@return [void]

    # File lib/nanoc3/base/item_rep.rb, line 242
    def forget_progress
      initialize_content
    end

inspect() click to toggle source

    # File lib/nanoc3/base/item_rep.rb, line 402
    def inspect
      "<#{self.class}:0x#{self.object_id.to_s(16)} name=#{self.name} binary=#{self.binary?} raw_path=#{self.raw_path} item.identifier=#{self.item.identifier}>"
    end

layout(layout_identifier) click to toggle source

Lays out the item using the given layout. This method will replace the content of the `:last` snapshot with the laid out content of the last snapshot.

This method is supposed to be called only in a compilation rule block (see {Nanoc3::CompilerDSL#compile}).

@param [String] layout_identifier The identifier of the layout the item should be laid out with

@return [void]

    # File lib/nanoc3/base/item_rep.rb, line 308
    def layout(layout_identifier)
      # Check whether item can be laid out
      raise Nanoc3::Errors::CannotLayoutBinaryItem.new(self) if self.binary?

      # Create "pre" snapshot
      snapshot(:pre) unless @content[:pre]

      # Create filter
      layout = layout_with_identifier(layout_identifier)
      filter, filter_name, filter_args = filter_for_layout(layout)

      # Layout
      @item.site.compiler.stack.push(layout)
      Nanoc3::NotificationCenter.post(:filtering_started, self, filter_name)
      @content[:last] = filter.run(layout.raw_content, filter_args)
      Nanoc3::NotificationCenter.post(:filtering_ended,   self, filter_name)
      @item.site.compiler.stack.pop

      # Create "post" snapshot
      snapshot(:post)
    end

outdated?() click to toggle source

@return [Boolean] true if this item rep’s output file is outdated and must be regenerated, false otherwise

    # File lib/nanoc3/base/item_rep.rb, line 172
    def outdated?
      !outdatedness_reason.nil?
    end

outdatedness_reason() click to toggle source

Calculates the reason why this item representation is outdated. The output will be a hash with a `:type` key, containing the reason why the item is outdated in the form of a symbol, and a `:description` key, containing a descriptive string that can be printed if necessary.

For documentation on the types that this method can return, check the {OUTDATEDNESS_REASON_DESCRIPTIONS} hash in this class.

@return [Hash, nil] A hash containing the reason why this item rep is

    outdated, both in the form of a symbol and as a descriptive string, or
    nil if the item representation is not outdated.

    # File lib/nanoc3/base/item_rep.rb, line 119
    def outdatedness_reason
      # Get reason symbol
      reason = lambda do
        # Outdated if we don't know
        return :no_mtime if @item.mtime.nil?

        # Outdated if the dependency tracker says so
        return :forced if @force_outdated

        # Outdated if compiled file doesn't exist (yet)
        return :no_raw_path if self.raw_path.nil?
        return :not_written if !File.file?(self.raw_path)

        # Get compiled mtime
        compiled_mtime = File.stat(self.raw_path).mtime

        # Outdated if file too old
        return :source_modified if @item.mtime > compiled_mtime

        # Outdated if layouts outdated
        return :layouts_outdated if @item.site.layouts.any? do |l|
          l.mtime.nil? || l.mtime > compiled_mtime
        end

        # Outdated if code outdated
        return :code_outdated if @item.site.code_snippets.any? do |cs|
          cs.mtime.nil? || cs.mtime > compiled_mtime
        end

        # Outdated if config outdated
        return :config_outdated if @item.site.config_mtime.nil?
        return :config_outdated if @item.site.config_mtime > compiled_mtime

        # Outdated if rules outdated
        return :rules_outdated if @item.site.rules_mtime.nil?
        return :rules_outdated if @item.site.rules_mtime > compiled_mtime

        return nil
      end[]

      # Build reason symbol and description
      if reason.nil?
        nil
      else
        {
          :type        => reason,
          :description => OUTDATEDNESS_REASON_DESCRIPTIONS[reason]
        }
      end
    end

snapshot(snapshot_name) click to toggle source

Creates a snapshot of the current compiled item content.

@param [Symbol] snapshot_name The name of the snapshot to create

@return [void]

    # File lib/nanoc3/base/item_rep.rb, line 335
    def snapshot(snapshot_name)
      target = self.binary? ? @filenames : @content
      target[snapshot_name] = target[:last]
    end

write() click to toggle source

Writes the item rep’s compiled content to the rep’s output file.

This method should not be called directly, even in a compilation block; the compiler is responsible for calling this method.

@return [void]

    # File lib/nanoc3/base/item_rep.rb, line 346
    def write
      # Create parent directory
      FileUtils.mkdir_p(File.dirname(self.raw_path))

      # Check if file will be created
      @created = !File.file?(self.raw_path)

      if self.binary?
        # Calculate hash of old content
        if File.file?(self.raw_path)
          hash_old = hash_for_file(self.raw_path)
          size_old = File.size(self.raw_path)
        end

        # Copy
        FileUtils.cp(@filenames[:last], self.raw_path)
        @written = true

        # Check if file was modified
        size_new = File.size(self.raw_path)
        hash_new = hash_for_file(self.raw_path) if size_old == size_new
        @modified = (size_old != size_new || hash_old != hash_new)
      else
        # Remember old content
        if File.file?(self.raw_path)
          @old_content = File.read(self.raw_path)
        end

        # Write
        File.open(self.raw_path, 'w') { |io| io.write(@content[:last]) }
        @written = true

        # Generate diff
        generate_diff

        # Check if file was modified
        @modified = File.read(self.raw_path) != @old_content
      end
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.