Class: MakeBook::Formats::HTML::Section

Inherits:
Object
  • Object
show all
Defined in:
lib/makebook/formats/html.rb

Overview

Section output

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source) ⇒ Section

Returns a new instance of Section.



110
111
112
# File 'lib/makebook/formats/html.rb', line 110

def initialize(source)
  @source = source
end

Instance Attribute Details

#sourceObject (readonly)

Returns the value of attribute source.



108
109
110
# File 'lib/makebook/formats/html.rb', line 108

def source
  @source
end

Instance Method Details

#imagesObject



165
166
167
# File 'lib/makebook/formats/html.rb', line 165

def images
  node.css('img').map { |img| [Asset.new(root + img['src']), img] }
end

#nodeObject



119
120
121
# File 'lib/makebook/formats/html.rb', line 119

def node
  @node ||= wrap(Nokogiri::HTML(source_document.to_html))
end

#rootObject



169
170
171
# File 'lib/makebook/formats/html.rb', line 169

def root
  source.dirname
end

#source_documentObject



114
115
116
117
# File 'lib/makebook/formats/html.rb', line 114

def source_document
  Kramdown::Document.new(File.read(source),
                         input: 'GFM', hard_wrap: false)
end

#to_htmlObject



123
124
125
# File 'lib/makebook/formats/html.rb', line 123

def to_html
  node.to_s
end

#toc(levels, ordered: false) ⇒ Object

rubocop:disable Metrics/AbcSize,Metrics/MethodLength



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/makebook/formats/html.rb', line 128

def toc(levels, ordered: false)
  fragment = Nokogiri::HTML.fragment('')
  tag = ordered ? 'ol' : 'ul'

  toc_elements(levels).reduce([fragment, nil]) do |(level, last), header|
    if last.nil? || last.name < header.name
      level << node = Nokogiri::XML::Node.new(tag, fragment).tap do |ul|
        ul['class'] = header.name
      end
      level = node
    elsif last.name > header.name
      level = level.parent
    end

    level << Nokogiri::XML::Node.new('li', fragment).tap do |li|
      li['class'] = header.name
      li << Nokogiri::XML::Node.new('a', fragment).tap do |a|
        a['href'] = "##{header['id']}"
        a.content = header.text
      end
    end

    [level, header]
  end

  fragment
end