Class: Quarto::Transformer

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

Overview

This abstract base class is a substitute for XSLT. Its transform method takes a single REXML::Element and applies rules defined in the subclass.

To define those rules, you subclass Transformer and write methods to handle each element type. For example:

class MyTranformer < Quarto::Transformer
  # This method will handle all <book> elements
  def transform_book(book_element, raise_on_unrecognized_element)
     # Return whatever string you like
     # raise_on_unrecognized_element is provided
     # so that you can pass it to recursive_transform
     # if necessary.
  end
end

Direct Known Subclasses

HtmlTransformer

Instance Method Summary collapse

Instance Method Details

#transform(element, raise_on_unrecognized_element = false) ⇒ Object

Recursively applies the transformation rules you’ve defined to element and its children, returning the results as a string. Depending on the rules you’ve set up, the result may be XML or something else altogether.

element must be a REXML::Element or a subclass thereof. If element is a REXML::Document, the document root and all its children will be transformed. If element is a REXML::Element, only the element’s descendents will be tranformed; element itself will not be used.

By default, unrecognized elements (and all their descendants) will be ommited from the result tree.

However, you can cause these unrecognized elements to raise an exception by setting raise_on_unrecognized_element to true.

Raises:

  • (ArgumentError)


40
41
42
43
44
45
46
47
48
49
# File 'lib/quarto/transformer.rb', line 40

def transform(element, raise_on_unrecognized_element = false)
  raise ArgumentError, "Expected REXML::Element but got #{element.inspect}" unless element.is_a?(REXML::Element)
  if element.is_a?(REXML::Document)
    recursive_transform(element.root, raise_on_unrecognized_element)
  else
    element.children.to_a.inject('') do |result, child|
      result + recursive_transform(child, raise_on_unrecognized_element)
    end
  end
end