Nanoc»Helpers

A helper is a module with functions that can be used during filtering.

Helpers need to be activated before they can be used. To activate a helper, include it, like this (in a file in the lib/ directory, such as lib/helpers.rb):

include Nanoc::Helpers::Blogging

Take a look at the helpers reference for a list of helpers that are included with Nanoc.

Writing helpers

To write a helper, create a file in the lib/ directory of the site. In that file, declare a module, and put your helper methods inside that module.

For example, the file lib/random_text.rb could contain this:

module RandomTextHelper
  def random_text
    "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do" \
    "eiusmod tempor incididunt ut labore et dolore magna aliqua."
  end
end

To use this helper, include it, for instance in lib/helpers.rb:

include RandomTextHelper

The methods provided by this helper can now be used during filtering. For example, the default layout, assuming it is filtered using ERB, can now generate random text like this:

<p><%= random_text %></p>

Pitfall: helper load order

Files in the lib/ directory are loaded alphabetically. This can cause Nanoc to try to include a helper before it is loaded.

For example, this situation will arise if helpers live in a lib/helpers/ directory, with the lib/helpers.rb file containing the #include calls:

% tree lib
lib
├── helpers.rb
└── helpers
    ├── link_to_id.rb
    └── toc.rb

The lib/helpers.rb file will be loaded before anything in lib/helpers/, and will thus result in an error such as NameError: uninitialized constant LinkToId.

To resolve this problem, rename lib/helpers.rb to lib/helpers_.rb, so that it gets loaded after the helpers have loaded:

% tree lib
lib
├── helpers
│   ├── link_to_id.rb
│   └── toc.rb
└── helpers_.rb