Skip to content

Instantly share code, notes, and snippets.

@jugglinmike
Last active January 3, 2016 02:09
Show Gist options
  • Save jugglinmike/8393545 to your computer and use it in GitHub Desktop.
Save jugglinmike/8393545 to your computer and use it in GitHub Desktop.
Concat filter for nanoc
module Nanoc::Filters
require 'pathname'
class Concat < Nanoc::Filter
identifier :concat
def item_pathname(item)
Pathname.new(File.join("content", item[:content_filename]))
end
# Concatenates files specified by the item's `sources` metadata. These
# files are loaded relative to the item's directory.
#
# @param [String] content The content to filter
#
# @return [String] The concatenated files or (if unspecified) the origina
# file content.
def run(content, params = {})
sources = assigns[:item].attributes[:sources]
if sources.kind_of?(Array)
if content != ""
throw "Concat filter: Items may not define both unique content and a `sources` list."
end
dependencies = []
#directory = Pathname.new(File.join("content", assigns[:item].path)).dirname.realpath
directory = self.item_pathname(assigns[:item]).dirname.realpath
content = sources.map do |file_name|
file_name = Pathname.new(file_name)
if file_name.relative?
file_name = directory + file_name
end
if !file_name.exist?
throw "Concat filter - Cannot locate file #{file_name}."
end
file_name = file_name.realpath
# Build list of nanoc items that the current item depends on
found = false
@items.each do |item|
if self.item_pathname(item).realpath == file_name
dependencies << item
found = true
break
end
end
if !found
throw "Concat filter - The file #{file_name} has no associated nanoc item."
end
File.read(file_name)
end.join("\n")
if dependencies.length > 0
depend_on dependencies
end
end
content
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment