class Bookshelf::Parser::HTML

Constants

EXTENSIONS

List of recognized extensions.

IGNORE_DIR

List of directories that should be skipped.

IGNORE_FILES

Files that should be skipped.

Public Instance Methods

content() click to toggle source

Return all chapters wrapped in a div.chapter tag.

# File lib/bookshelf/parser/html.rb, line 34
def content
  @content ||= String.new.tap do |chapters|
    entries.each do |entry|
      chapters << %[<div class="chapter">#{render_file(entry)}</div>]
    end
  end
end
parse() click to toggle source

Parse all files and save the parsed content to output/book_name.html.

# File lib/bookshelf/parser/html.rb, line 19
def parse
  File.open(Bookshelf.root_dir.join("output/#{name}.html"), "w") do |file|
    locals = config.merge({
      :content => content,
      :toc => toc
    })
    file << Bookshelf.render_template(Bookshelf.root_dir.join("templates/html/layout.erb"), locals)
  end
  true
rescue Exception
  false
end
toc() click to toggle source
# File lib/bookshelf/parser/html.rb, line 42
def toc
  if @toc.blank?
    @toc = ""
    Nokogiri::HTML(content).css(".chapter h2:first-of-type").each do |xml|
      @toc << %[<div><a href="##{xml.attribute("id")}"><span>#{CGI.escape_html(xml.text)}</span></a></div>]
    end
  end
  return @toc
end

Private Instance Methods

entries() click to toggle source

Return a list of all recognized files.

# File lib/bookshelf/parser/html.rb, line 56
def entries
  Dir.entries(book_dir).sort.inject([]) do |buffer, entry|
    buffer << book_dir.join(entry) if valid_entry?(entry)
    buffer
  end
end
format(file) click to toggle source
# File lib/bookshelf/parser/html.rb, line 90
def format(file)
  case File.extname(file).downcase
  when ".markdown", ".mkdn", ".md"
    :markdown
  else
    :html
  end
end
render_file(file) click to toggle source

Render file considering its extension.

# File lib/bookshelf/parser/html.rb, line 79
def render_file(file)
  file_format = format(file)
  content = File.read(file)
  content = case file_format
  when :markdown
    Markdown.to_html(content)
  else
    content
  end
end
valid_entry?(entry) click to toggle source

Check if path is a valid entry. Files that start with a dot or underscore will be skipped.

# File lib/bookshelf/parser/html.rb, line 66
def valid_entry?(entry)
  entry !~ /^(\.|_)/ && valid_file?(entry)
end
valid_file?(entry) click to toggle source

Check if path is a valid file.

# File lib/bookshelf/parser/html.rb, line 72
def valid_file?(entry)
  ext = File.extname(entry).gsub(/\./, "").downcase
  File.file?(book_dir.join(entry)) && EXTENSIONS.include?(ext) && entry !~ IGNORE_FILES
end