Class: HtmlTagBuilder

Inherits:
Object show all
Defined in:
lib/common/html_tag_builder.rb

Overview

tag.ul do |n|

1.upto(3) do |num|
  n.li do |n|
    n.i '.arrow'
    n.span num
  end
end

end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeHtmlTagBuilder

Returns a new instance of HtmlTagBuilder.



59
60
61
# File 'lib/common/html_tag_builder.rb', line 59

def initialize
  @data = []
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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

forward to class



64
65
66
# File 'lib/common/html_tag_builder.rb', line 64

def method_missing tag_name, *args, &block
  @data.push self.class.tag(tag_name, args[0], args[1], &block)
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



57
58
59
# File 'lib/common/html_tag_builder.rb', line 57

def data
  @data
end

Class Method Details

.build(attrs, node = nil, text = nil) ⇒ Object

build html node



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/common/html_tag_builder.rb', line 41

def build attrs, node=nil, text=nil
  opts = ''
  attrs.each do |k,v|
    opts += ' '+k.to_s.gsub(/_/,'-')+'="'+v.to_s.gsub(/"/,'"')+'"' if v.present?
  end

  return opts unless node

  text = yield opts if block_given?
  text ||= '' unless ['input', 'img', 'meta', 'link', 'hr', 'br'].include?(node.to_s)
  text ? %{<#{node}#{opts}>#{text}</#{node}>} : %{<#{node}#{opts} />}
end

.method_missing(tag_name, *args, &block) ⇒ Object

tag.div -> tag.tag :div



13
14
15
# File 'lib/common/html_tag_builder.rb', line 13

def method_missing tag_name, *args, &block
  tag tag_name, args[0], args[1], &block
end

.tag(name = nil, opts = {}, data = nil) ⇒ Object

tag :div, { ‘class’=>‘iform’ } do



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/common/html_tag_builder.rb', line 18

def tag name=nil, opts={}, data=nil
  # covert tag.a '.foo.bar' to class names
  if opts.class == String && opts[0,1] == '.'
    opts = { class: opts.sub('.', '').gsub('.', ' ') }
  end

  # fix data and opts unless opts is Hash
  data, opts = opts, {} unless opts.class == Hash

  if block_given?
    inline = new
    data = yield(inline, opts)

    # if data is pushed to passed node, use that data
    data = inline.data if inline.data.first
  end

  data = data.join('') if data.is_a?(Array)

  build opts, name, data
end