Class: HtmlWriter

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

Defined Under Namespace

Classes: InvalidTagError

Constant Summary collapse

VERSION =
'0.2.0'
DEFAULT_DOCTYPE =
5
VALID_TAGS =
{
  5 => [
    :a, :abbr, :address, :area, :article, :aside, :audio,
    :b, :base, :bdi, :bdo, :big, :blockquote, :body, :br, :button,
    :canvas, :caption, :cite, :code, :col, :colgroup, :command,
    :datalist, :dd, :del, :details, :dfn, :div, :dl, :dt,
    :em, :embed,
    :fieldset, :figcaption, :figure, :footer, :form,
    :h1, :h2, :h3, :h4, :h5, :h6, :head, :header, :hr,
    :i, :iframe, :img, :input, :ins,
    :keygen, :kbd,
    :label, :legend, :li, :link,
    :map, :mark, :menu, :meta, :meter,
    :nav, :noscript,
    :object, :ol, :optgroup, :option, :output,
    :p, :param, :pre, :progress,
    :q,
    :rp, :rt, :ruby,
    :s, :samp, :script, :section, :select, :small, :source, :span, :strong,
        :style, :sub, :summary, :sup,
    :table, :tbody, :td, :textarea, :tfoot, :th, :thead, :time, :title, :tr,
        :track,
    :u, :ul,
    :var, :video,
    :wbr
  ]
}

Instance Method Summary collapse

Constructor Details

#initializeHtmlWriter

Returns a new instance of HtmlWriter.



36
37
38
39
# File 'lib/html_writer.rb', line 36

def initialize
  @html    = ''
  @doctype = DEFAULT_DOCTYPE
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/html_writer.rb', line 59

def method_missing(name, *args, &block)
  unless valid_tag?(name)
    raise InvalidTagError, "`<#{name}>` is not a valid HTML #{@doctype} tag."
  end
  
  @html << "<#{name}>"
  if block_given?
    yield self
  else
    @html << args.join('')
  end
  @html << "</#{name}>"
end

Instance Method Details

#doctype(doctype) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/html_writer.rb', line 51

def doctype(doctype)
  @doctype = doctype
  case @doctype
  when 5
    @html = '<!DOCTYPE html>' + @html
  end
end

#write {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:

  • _self (HtmlWriter)

    the object that the method was called on



41
42
43
44
45
# File 'lib/html_writer.rb', line 41

def write
  @html << '<html>'
  yield self
  @html << '</html>'
end

#write_inline {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:

  • _self (HtmlWriter)

    the object that the method was called on



47
48
49
# File 'lib/html_writer.rb', line 47

def write_inline
  yield self
end