class HTMLBuilder
HTML文法に従ったドキュメントを構築するクラス。 XMLパーザを使わずRubyだけで書かれている。 簡明のためDOM操作機能はない。
Constants
- BLOCKY_ELEMS
出力結果HTMLを読みやすくするため前後に改行を挿入するタグ。
- VOID_ELEMS
Public Class Methods
good_name?(str)
click to toggle source
引数strが属性名として適切な文字列の場合に真を返す。 現状実装はHTML文法で許される名前のリストまでは判別していない。
# File html_builder.rb, line 20 def good_name? str /\A[0-9A-Za-z][-0-9A-Za-z]*\z/ === str end
new(title)
click to toggle source
# File html_builder.rb, line 35 def initialize title qtitle = HTMLBuilder.xmltext(title) @buf = ['<!DOCTYPE html>'] # @head holds the content of <head> tag until _start_body is called. # _start_body clears it to indicate <head> can no longer be modified. @head = { :lang => 'ja', :title => qtitle, :buf => [] } # @stack is list of nested tags @stack = [] end
xmlattr(str)
click to toggle source
caution: double quotes added
# File html_builder.rb, line 14 def xmlattr str str.to_s.encode(Encoding::UTF_8, :xml => :attr) end
xmltext(str)
click to toggle source
# File html_builder.rb, line 9 def xmltext str str.to_s.encode(Encoding::UTF_8, :xml => :text) end
Public Instance Methods
close_tag()
click to toggle source
# File html_builder.rb, line 79 def close_tag raise ArgumentError 'already closed HTML' if @stack.empty? name = @stack.pop @buf.push('</', name, ">") _newline if BLOCKY_ELEMS === name end
header(item, attrs = {})
click to toggle source
# File html_builder.rb, line 49 def header item, attrs = {} raise ArgumentError '<head> already frozen' if @head.empty? case item when 'lang' @head[:lang] = attrs.to_s when 'title' @head[:title] = attrs.to_s when 'base', 'meta', 'link', 'isindex', 'script', 'style' @head[:buf].push [item, attrs] else raise ArgumentError "<#{item}> not for <head>" end end
puts(str)
click to toggle source
# File html_builder.rb, line 72 def puts str _start_body @buf.push HTMLBuilder.xmltext(str) end
Also aliased as: <<
table(cols, opts = {}) { |self| ... }
click to toggle source
# File html_builder.rb, line 86 def table cols, opts = {} tag('table') { tag('thead') { tag('caption') { puts(opts[:caption]) } if opts[:caption] tag('tr') { cols.each {|colname| tag('th') { self.puts(colname) } } } } tag('tbody') { yield self } } end
tag(name, attrs = {}) { |self| ... }
click to toggle source
# File html_builder.rb, line 63 def tag name, attrs = {} _start_body if block_given? _tag(name, attrs) { yield self } else _tag(name, attrs) end end
to_s()
click to toggle source
# File html_builder.rb, line 112 def to_s close_all_tags @buf.flatten.join end
write(output=$stdout)
click to toggle source
# File html_builder.rb, line 106 def write output=$stdout close_all_tags output.set_encoding(Encoding::UTF_8) @buf.each {|str| output << str } end