Class: HTMLPage

Inherits:
Object
  • Object
show all
Defined in:
lib/html_page.rb

Defined Under Namespace

Classes: Figure, PageAttributes

Constant Summary collapse

Attributes =

user-defined attributes

i(author description keywords layout robots title)
TEMPLATES_DIR =
'./templates/'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content_filename, layout_filename = nil) ⇒ HTMLPage

Compile an HTML page from the content_filename and layout_filename sources.

Content files must be markdown or embedded ruby and have an “md” or “erb” extension. If markdown, content is first evaluated as Erb. Layouts files must be “erb”. The content renders within the layout template if specified.

Attributes specified in the preamble of the content file will be set in page and are available to layout and embedded templates.



25
26
27
28
29
# File 'lib/html_page.rb', line 25

def initialize(content_filename, layout_filename = nil)
  @content_filename = content_filename
  @layout_filename  = layout_filename&.delete_prefix(TEMPLATES_DIR)
  @page = PageAttributes.new
end

Instance Attribute Details

#pageObject (readonly)

Returns the value of attribute page.



10
11
12
# File 'lib/html_page.rb', line 10

def page
  @page
end

Instance Method Details

#renderObject

Returns the rendered HTML page.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/html_page.rb', line 34

def render
  f = File.new(@content_filename)

  # parse attributes and content
  while (line = f.gets)
    case line
    when /^(\w+):(.*)/  # begin attribute
      begin
        attribute = page[$1.downcase] = $2.strip
      rescue NameError => e
        raise e.class, "Bad page attribute `#{$1}'.\n"\
          "Valid attributes: #{Attributes.to_s.tr('[:]','')}"
      end
    when /^\s*$/        # end attribute (blank lines between attrs)
      attribute = nil
    else
      unless attribute  # remainder is content
        content = line
        content << f.gets(nil) unless f.eof?
        break
      end
      attribute << (attribute.empty? ? '':' ') << line.strip
    end
  end

  f.close
  content = instance_eval(transform(content)).call # process with erb

  if @content_filename.end_with? '.md'
    if page.title.nil? # then use H1
      page.title = content[/^#\s+([^#\{\r\n]+)/, 1]&.rstrip
    end
    opts = { auto_ids: false }
    content = Kramdown::Document.new(content, opts).to_html
  end

  if @layout_filename
    page.content = content
    template(@layout_filename) # page.content embedded in layout
  else
    content # without a layout
  end
end