Skip to content

Instantly share code, notes, and snippets.

@retorquere
Created June 17, 2011 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save retorquere/1031503 to your computer and use it in GitHub Desktop.
Save retorquere/1031503 to your computer and use it in GitHub Desktop.
require 'nokogiri'
class HTMLPage < Nanoc3::Filter
identifier :htmlpage
type :text
def run(content, params={})
page = Nokogiri::HTML(content)
begin
@item[:title] = page.at('//title').content
rescue NoMethodError
@item[:title] = File.basename(@item[:filename], File.extname(@item[:filename]))
end
begin
@item[:description] = page.at("//meta[@name='description']")['content']
rescue NoMethodError
#pass
end
@item[:menu] = Menu.new(@item[:filename])
return page.at('//body').children.to_s
end
end
require 'nokogiri'
class Menu
def initialize(filename)
@filename = filename.gsub(/^content\//, '')
@level = nil
@path = nil
if File.exists?('content/sitemap.html')
sitemap = Nokogiri::HTML(open('content/sitemap.html'))
sitemap.xpath("//a[@href='#{@filename}']").each {|a|
level = a.path.split('/ul/').size - 1
if @level.nil? || level > @level
@level = level
@path = a.path
end
}
end
@cache = {}
end
def menu(start, levels=nil)
return nil unless @path
# levels below start
maxlevels = @level - start + 1
levels ||= maxlevels
levels = maxlevels if levels > maxlevels
return nil if levels == 0
key = "#{start}-#{levels}"
if @cache[key].nil?
sitemap = Nokogiri::HTML(open('content/sitemap.html'))
# mark selected path
path = @path.gsub(/\/a$/, '/').split('/')
path.each_with_index{|elt, i|
sitemap.at(path[0 .. i].join('/'))['class'] = 'selected' if elt =~ /li/
}
# skip levels above start
path = @path.gsub(/\/li(\[[0-9]+\])?\/a$/, '/')
path = path.split('/ul/')[0,start].join('/ul/') + '/ul'
m = sitemap.xpath(path)
# prune unwanted levels
path = './/' + (['ul'] * (levels)).join('//')
m.xpath(path).remove
# fix links
m.xpath('.//a').each {|a|
next if a['href'] =~ /^http/ || a['href'] =~ /^\//
a['href'] = Pathname.new(a['href']).relative_path_from(Pathname.new(File.dirname(@filename)))
}
@cache[key] = m.to_s
end
return @cache[key]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment