Module: Nanoc3::Helpers::Blogging

### Home Classes Methods

### In Files

- lib/nanoc3/helpers/blogging.rb

### Methods

- #articles
- #atom_feed
- #atom_tag_for
- #feed_url
- #sorted_articles
- #url_for

### 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::Helpers::Blogging

Provides functionality for building blogs, such as finding articles and constructing feeds.

This helper has a few requirements. First, all blog articles should have the following attributes:

- `kind` — Set to `“article”`

- `created_at` — The article’s publication timestamp

Some functions in this blogging helper, such as the {atom_feed} function, require additional attributes to be set; these attributes are described in the documentation for these functions.

All “time” item attributes, site configuration attributes or method parameters can either be a `Time` instance or a string in any format parseable by `Time.parse`.

The two main functions are {sorted_articles} and {atom_feed}.

### Public Instance Methods

articles() click to toggle source

Returns an unsorted list of articles, i.e. items where the `kind` attribute is set to `“article”`.

@return [Array] An array containing all articles

    # File lib/nanoc3/helpers/blogging.rb, line 29
    def articles
      @items.select { |item| item[:kind] == 'article' }
    end

atom_feed(params={}) click to toggle source

Returns a string representing the atom feed containing recent articles, sorted by descending creation date.

The following attributes must be set on blog articles:

- `title` — The title of the blog post

- `kind` and `created_at` (described above)

The following attributes can optionally be set on blog articles to change the behaviour of the Atom feed:

- `excerpt` — An excerpt of the article, which is usually only a few lines long.

- `custom_path_in_feed` — The path that will be used instead of the normal path in the feed. This can be useful when including non-outputted items in a feed; such items could have their custom feed path set to the blog path instead, for example.

- `custom_url_in_feed` — The url that will be used instead of the normal url in the feed (generated from the site’s base url + the item rep’s path). This can be useful when building a link-blog where the URL of article is a remote location.

- `updated_at` — The time when the article was last modified. If this attribute is not present, the `created_at` attribute will be used as the time when the article was last modified.

The site configuration will need to have the following attributes:

- `base_url` — The URL to the site, without trailing slash. For example, if the site is at “example.com/”, the `base_url` would be “example.com”.

The feed item will need to know about the feed title, the feed author name, and the URI corresponding to the author. These can be specified using parameters, as attributes in the feed item, or in the site configuration.

- `title` — The title of the feed, which is usually also the title of the blog.

- `author_name` — The name of the item’s author.

- `author_uri` — The URI for the item’s author, such as the author’s web site URL.

The feed item can have the following optional attributes:

- `feed_url` — The custom URL of the feed. This can be useful when the private feed URL shouldn’t be exposed; for example, when using FeedBurner this would be set to the public FeedBurner URL.

To construct a feed, create a new item and make sure that it is filtered with `:erb` or `:erubis`; it should not be laid out. Ensure that it is routed to the proper path, e.g. `/blog.xml`. It may also be useful to set the `is_hidden` attribute to true, so that helpers such as the sitemap helper will ignore the item. The content of the feed item should be `<%= atom_feed %>`.

@example Defining compilation and routing rules for a feed item

    compile '/blog/feed/' do
      filter :erb
    end

    route '/blog/feed/' do
      '/blog.xml'
    end

@example Limiting the number of items in a feed

    <%= atom_feed :limit => 5 %>

@option params [Number] :limit (5) The maximum number of articles to show

@option params [Array] :articles (sorted_articles) A list of articles to include in the feed

@option params [Proc] :content_proc (->{ |article| article.compiled_content(:snapshot => :pre) }) A proc that returns the content of the given article, which is passed as a parameter. This function may not return nil.

@option params [proc] :excerpt_proc (->{ |article| article }) A proc that returns the excerpt of the given article, passed as a parameter. This function should return nil if there is no excerpt.

@option params [String] :title The feed’s title, if it is not given in the item attributes.

@option params [String] :author_name The name of the feed’s author, if it is not given in the item attributes.

@option params [String] :author_uri The URI of the feed’s author, if it is not given in the item attributes.

@return [String] The generated feed content

    # File lib/nanoc3/helpers/blogging.rb, line 146
    def atom_feed(params={})
      require 'builder'
      require 'time'

      # Extract parameters
      limit             = params[:limit] || 5
      relevant_articles = params[:articles] || articles || []
      content_proc      = params[:content_proc] || lambda { |a| a.compiled_content(:snapshot => :pre) }
      excerpt_proc      = params[:excerpt_proc] || lambda { |a| a[:excerpt] }

      # Check config attributes
      if @site.config[:base_url].nil?
        raise RuntimeError.new('Cannot build Atom feed: site configuration has no base_url')
      end

      # Check feed item attributes
      title = params[:title] || @item[:title] || @site.config[:title]
      if title.nil?
        raise RuntimeError.new('Cannot build Atom feed: no title in params, item or site config')
      end
      author_name = params[:author_name] || @item[:author_name] || @site.config[:author_name]
      if author_name.nil?
        raise RuntimeError.new('Cannot build Atom feed: no author_name in params, item or site config')
      end
      author_uri = params[:author_uri] || @item[:author_uri] || @site.config[:author_uri]
      if author_uri.nil?
        raise RuntimeError.new('Cannot build Atom feed: no author_uri in params, item or site config')
      end

      # Check article attributes
      if relevant_articles.empty?
        raise RuntimeError.new('Cannot build Atom feed: no articles')
      end
      if relevant_articles.any? { |a| a[:created_at].nil? }
        raise RuntimeError.new('Cannot build Atom feed: one or more articles lack created_at')
      end

      # Get sorted relevant articles
      sorted_relevant_articles = relevant_articles.sort_by do |a|
        time = a[:created_at]
        time.is_a?(String) ? Time.parse(time) : time
      end.reverse.first(limit)

      # Get most recent article
      last_article = sorted_relevant_articles.first

      # Create builder
      buffer = ''
      xml = Builder::XmlMarkup.new(:target => buffer, :indent => 2)

      # Build feed
      xml.instruct!
      xml.feed(:xmlns => 'http://www.w3.org/2005/Atom') do
        root_url = @site.config[:base_url] + '/'

        # Add primary attributes
        xml.id      root_url
        xml.title   title

        # Add date
        time = last_article[:created_at]
        xml.updated((time.is_a?(String) ? Time.parse(time) : time).to_iso8601_time)

        # Add links
        xml.link(:rel => 'alternate', :href => root_url)
        xml.link(:rel => 'self',      :href => feed_url)

        # Add author information
        xml.author do
          xml.name  author_name
          xml.uri   author_uri
        end

        # Add articles
        sorted_relevant_articles.each do |a|
          # Get URL
          url = url_for(a)
          next if url.nil?

          xml.entry do
            # Add primary attributes
            xml.id        atom_tag_for(a)
            xml.title     a[:title], :type => 'html'

            # Add dates
            create_time = a[:created_at]
            update_time = a[:updated_at] || a[:created_at]
            xml.published((create_time.is_a?(String) ? Time.parse(create_time) : create_time).to_iso8601_time)
            xml.updated(  (update_time.is_a?(String) ? Time.parse(update_time) : update_time).to_iso8601_time)

            # Add link
            xml.link(:rel => 'alternate', :href => url)

            # Add content
            summary = excerpt_proc.call(a)
            xml.content   content_proc.call(a), :type => 'html'
            xml.summary   summary, :type => 'html' unless summary.nil?
          end
        end
      end

      buffer
    end

atom_tag_for(item) click to toggle source

Returns an URI containing an unique ID for the given item. This will be used in the Atom feed to uniquely identify articles. These IDs are created using a procedure suggested by Mark Pilgrim and described in his

“How to make a good ID in Atom” blog post

  (diveintomark.org/archives/2004/05/28/howto-atom-id).

  @param [Nanoc3::Item] item The item for which to create an atom tag

  @return [String] The atom tag for the given item

    # File lib/nanoc3/helpers/blogging.rb, line 294
    def atom_tag_for(item)
      require 'time'

      hostname, base_dir = %{^.+?://([^/]+)(.*)$}.match(@site.config[:base_url])[1..2]

      time = item[:created_at]
      formatted_date = (time.is_a?(String) ? Time.parse(time) : time).to_iso8601_date

      'tag:' + hostname + ',' + formatted_date + ':' + base_dir + (item.path || item.identifier)
    end

feed_url() click to toggle source

Returns the URL of the feed. It will return the custom feed URL if set, or otherwise the normal feed URL.

@return [String] The URL of the feed

    # File lib/nanoc3/helpers/blogging.rb, line 276
    def feed_url
      # Check attributes
      if @site.config[:base_url].nil?
        raise RuntimeError.new('Cannot build Atom feed: site configuration has no base_url')
      end

      @item[:feed_url] || @site.config[:base_url] + @item.path
    end

sorted_articles() click to toggle source

Returns a sorted list of articles, i.e. items where the `kind` attribute is set to `“article”`. Articles are sorted by descending creation date, so newer articles appear before older articles.

@return [Array] A sorted array containing all articles

    # File lib/nanoc3/helpers/blogging.rb, line 38
    def sorted_articles
      require 'time'
      articles.sort_by do |a|
        time = a[:created_at]
        time.is_a?(String) ? Time.parse(time) : time
      end.reverse
    end

url_for(item) click to toggle source

Returns the URL for the given item. It will return the URL containing the custom path in the feed if possible, otherwise the normal path.

@param [Nanoc3::Item] item The item for which to fetch the URL.

@return [String] The URL of the given item

    # File lib/nanoc3/helpers/blogging.rb, line 256
    def url_for(item)
      # Check attributes
      if @site.config[:base_url].nil?
        raise RuntimeError.new('Cannot build Atom feed: site configuration has no base_url')
      end

      # Build URL
      if item[:custom_url_in_feed]
        item[:custom_url_in_feed]
      elsif item[:custom_path_in_feed]
        @site.config[:base_url] + item[:custom_path_in_feed]
      elsif item.path
        @site.config[:base_url] + item.path
      end
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.