Class: Wee::HtmlWriter

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

Overview

A class used to write out HTML documents easily.

Usage:

w = Wee::HtmlWriter.new(doc='')
w.start_tag('html')
w.start_tag('body')
w.start_tag('a', 'href' => 'http://...')
w.text('link')
w.end_tag('a')
w.end_tag('body')
w.end_tag('html')

p doc  # => '<html><body><a href="http://...">link</a></body></html>'

Direct Known Subclasses

HtmlDocument

Constant Summary collapse

CLOSING =
">".freeze
SINGLE_CLOSING =
" />".freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(port = []) ⇒ HtmlWriter

Returns a new instance of HtmlWriter.



25
26
27
# File 'lib/wee/html_writer.rb', line 25

def initialize(port=[])
  @port = port
end

Instance Attribute Details

#portObject

Returns the value of attribute port.



23
24
25
# File 'lib/wee/html_writer.rb', line 23

def port
  @port
end

Instance Method Details

#encode_text(str) ⇒ Object



60
61
62
# File 'lib/wee/html_writer.rb', line 60

def encode_text(str)
  @port << Rack::Utils.escape_html(str.to_s)
end

#end_tag(tag) ⇒ Object



52
53
54
# File 'lib/wee/html_writer.rb', line 52

def end_tag(tag)
  @port << "</#{tag}>"
end

#single_tag(tag, attributes = nil) ⇒ Object



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

def single_tag(tag, attributes=nil)
  start_tag(tag, attributes, true)
end

#start_tag(tag, attributes = nil, single = false) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/wee/html_writer.rb', line 32

def start_tag(tag, attributes=nil, single=false)
  if attributes
    @port << "<#{tag}"
    attributes.each {|k, v| 
      if v
        @port << %[ #{ k }="#{ v }"] 
      else
        @port << %[ #{ k }] 
      end
    }
    @port << (single ? SINGLE_CLOSING : CLOSING)
  else
    @port << (single ? "<#{tag} />" : "<#{tag}>")
  end
end

#text(str) ⇒ Object



56
57
58
# File 'lib/wee/html_writer.rb', line 56

def text(str)
  @port << str.to_s
end

#write(str) ⇒ Object Also known as: <<



64
65
66
# File 'lib/wee/html_writer.rb', line 64

def write(str)
  @port << str
end