Class: Docter::ToC

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/docter/common.rb

Overview

Table of contents.

A ToC is an array of entries, each entry providing a link to and a title, and may itself be a ToC.

Supports the Enumerable methods for operating on the entries, in addition to the methods each, first/last, size, empty? and index/include?. Use #add to create new entries.

Use #to_html to transform to an HTML ordered list.

Direct Known Subclasses

ToCEntry

Constant Summary collapse

ARRAY_METHODS =
["each", "first", "last", "size", "empty?", "include?", "index", "[]"]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeToC

Create new ToC with no entries.



215
216
217
# File 'lib/docter/common.rb', line 215

def initialize()
  @entries = []
end

Instance Attribute Details

#entriesObject (readonly)

Array of entries.



212
213
214
# File 'lib/docter/common.rb', line 212

def entries
  @entries
end

Instance Method Details

#add(*args) ⇒ Object

:call-seq:

add(url, title) => entry
add(entry) => entry

Adds (and returns) a new entry. The first form creates an entry with a link (must be a valid URL, use CGI.escape if necessary) and HTML-encoded title. The second form adds an existing entry, for example to a page.



231
232
233
234
235
236
237
238
239
240
# File 'lib/docter/common.rb', line 231

def add(*args)
  if ToCEntry === args.first
    entry = args.shift
    raise ArgumentError, "Can only accept a ToCEntry argument." unless args.empty?
  else
    entry = ToCEntry.new(*args)
  end
  entries << entry
  entry
end

#to_html(*args) ⇒ Object

:call-seq:

to_html(options) => html

Transforms this ToC into an HTML ordered list (OL) by calling to_html on each ToC entry.

You can use the following options:

  • :nested – For entries that are also ToC, expands them as well. You can specify how many levels (e.g. 1 to expand only once), or true to expand all levels.

  • :class – Class to apply to the OL element.

The options argument can take the form of a Hash, list of symbols or both. Symbols are treated as true for example:

to_html(:nested, :class=>"toc")

Is the same as:

to_html(:nested=>true, :class=>"toc")


257
258
259
260
261
262
# File 'lib/docter/common.rb', line 257

def to_html(*args)
  options = Hash === args.last ? args.pop.clone : {}
  args.each { |arg| options[arg.to_sym] = true }
  cls = %{ class="#{options[:class]}"} if options[:class]
  %{<ol #{cls}>#{map { |entry| entry.to_html(options) }}</ol>}
end