lib/cosensee/html_builder.rb in cosensee-0.6.0 vs lib/cosensee/html_builder.rb in cosensee-0.8.0

- old
+ new

@@ -6,54 +6,63 @@ require 'fileutils' module Cosensee # generate HTML files class HtmlBuilder - def initialize(project, root_dir: nil) + def initialize(project, output_dir: nil, css_dir: nil, base_url: nil) @project = project @templates_dir = File.join(__dir__, '../../templates') - @root_dir = root_dir || File.join(Dir.pwd, '.out') - FileUtils.mkdir_p(@root_dir) + @output_dir = output_dir || File.join(Dir.pwd, Cosensee::DEFAULT_OUTPUT_DIR) + @css_dir = css_dir || Cosensee::DEFAULT_CSS_DIR + @base_url = base_url + FileUtils.mkdir_p(@output_dir) end - attr_reader :project, :root_dir, :templates_dir + attr_reader :project, :output_dir, :css_dir, :templates_dir, :base_url - def build_all + def build_all(clean: true) + purge_files if clean + build_index(project) # build all pages project.pages.each do |page| build_page(page) end # build all orphan (title only) pages - project.page_store.orphan_page_titles.each do |title| + project.orphan_page_titles.each do |title| build_page_only_title(title) end end def build_index(project) - template = Tilt::ErubiTemplate.new(File.join(templates_dir, 'index.html.erb')) - output = template.render(nil, project:) - File.write(File.join(root_dir, 'index.html'), output) + render_html(src: 'index.html.erb', to: 'index.html', project:, css_dir:, base_url:) end def build_page(page) - template = Tilt::ErubiTemplate.new(File.join(templates_dir, 'page.html.erb')) - output = template.render(nil, project:, page:, title: page.title) - File.write(File.join(root_dir, page.link_path), output) + render_html(src: 'page.html.erb', to: page.link_path, project:, css_dir:, page:, title: page.title, base_url:) end def build_page_only_title(title) - path = File.join(root_dir, "#{title.gsub(/ /, '_').gsub('/', '%2F')}.html") + path = File.join(output_dir, "#{title.gsub(/ /, '_').gsub('/', '%2F')}.html") return if File.exist?(path) - template = Tilt::ErubiTemplate.new(File.join(templates_dir, 'page.html.erb')) - output = template.render(nil, project:, page: nil, title:) + # make a dummy page + page = Page.new(title:, id: 0, created: Time.now, updated: Time.now, views: 0, lines: []) + + template = Tilt::ErubiTemplate.new(File.join(templates_dir, 'page.html.erb'), escape_html: true) + output = template.render(nil, project:, page:, title:, css_dir:, base_url:) File.write(path, output) end - def page_title(page) - "#{page.title} | #{project.title}" + def purge_files + FileUtils.rm_rf(Dir.glob("#{output_dir}/*.html")) + end + + def render_html(src:, to:, **args) + template = Tilt::ErubiTemplate.new(File.join(templates_dir, src), escape_html: true) + output = template.render(nil, **args) + File.write(File.join(output_dir, to), output) end end end