Class: HtmlBuilderNode

Inherits:
Object
  • Object
show all
Defined in:
lib/html-builder.rb

Constant Summary collapse

INDENT =
"\t"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent, name, *args) ⇒ HtmlBuilderNode

Returns a new instance of HtmlBuilderNode.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/html-builder.rb', line 4

def initialize parent, name, *args
  @attrs = args.last.is_a?(Hash) ? args.pop : {}
  @name = name
  if not args.empty?
    @text = args.collect do |a|
      if a.is_a? HtmlBuilderNode
        parent.children.delete a
        a.to_s(0, true)
      else
        a.to_s
      end
    end.join
  end
  parent.children << self if parent
  @children = []
end

Instance Attribute Details

#childrenObject

Returns the value of attribute children.



20
21
22
# File 'lib/html-builder.rb', line 20

def children
  @children
end

Instance Method Details

#format_node_innerObject



21
22
23
# File 'lib/html-builder.rb', line 21

def format_node_inner
  [@name, *@attrs.collect{|k,v| "#{k}=\"#{v}\""}].join ' '
end

#to_s(ind = 0, inl = false) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/html-builder.rb', line 24

def to_s ind = 0, inl = false
  raise "Cannot own text and child both!" if @text and not @children.empty?
  if inl
    if @text
      return "<#{format_node_inner}>#{@text}</#{@name}>"
    elsif not @children.empty?
      return ["<#{format_node_inner}>", *@children.collect{|c| c.to_s 0, true}, "</#{@name}>"].join
    else
      return "<#{format_node_inner}/>"
    end
  else
    if @text
      return "#{INDENT * ind}<#{format_node_inner}>#{@text}</#{@name}>\n"
    elsif not @children.empty?
      return ["#{INDENT * ind}<#{format_node_inner}>\n", *@children.collect{|c| c.to_s(ind + 1)}, "#{INDENT * ind}</#{@name}>\n"].join
    else
      return "#{INDENT * ind}<#{format_node_inner}/>\n"
    end
  end
end