Class: Html

Inherits:
Object show all
Includes:
Enumerable
Defined in:
lib/iron/web/html.rb,
lib/iron/web/html/element.rb

Overview

HTML Element Class

Used with the Html class to generate html content for a single tag/element. Represents a single element with attributes and optional contents (including other elements). Generally, you won’t use this by itself. Check out Html.build() instead.

Simple useage:

>> Html::Element.new('span','some text', :id => 'title-text').render
=> '<span id="title-text">some text</span>'

Complex usage:

span = Html::Element.new('span')   # Creates a span element for customization
span.id = 'title-text'       # Set some attributes
span.style = 'color: #f00;'
span.html = 'some text'      # Adds some content
span.render                  # Converts to html string
=> '<span id="title-text" style="color: #f00;">some text</span>

Defined Under Namespace

Classes: Element

Constant Summary collapse

HTML_ESCAPE =

Constants

{"&"=>"&amp;", ">"=>"&gt;", "<"=>"&lt;", "\""=>"&quot;"}.freeze
JS_ESCAPE =
{'\\' => '\\\\', '</' => '<\/', "\r\n" => '\n', "\n" => '\n', "\r" => '\n', '"' => '\\"', "'" => "\\'"}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize {|_self| ... } ⇒ Html

Sets up internal state, natch, and accepts a block that customizes the resulting object.

Yields:

  • (_self)

Yield Parameters:

  • _self (Html)

    the object that the method was called on



76
77
78
79
80
# File 'lib/iron/web/html.rb', line 76

def initialize
  @items = []
  @item_stack = []
  yield self if block_given?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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

Creates a new element on any method missing calls. Returns self, so you can chain calls (eg html.div(‘foo’).span(‘bar’) )



137
138
139
140
141
142
143
144
145
146
# File 'lib/iron/web/html.rb', line 137

def method_missing(method, *args, &block)
  parts = method.to_s.match(/^([a-z]+[0-9]?)$/)
  if parts
    # Assume it's a new element, create the tag
    tag(parts[1], *args, &block)
  else
    # There really is no method...
    super
  end
end

Class Method Details

.build {|builder| ... } ⇒ Object

Primary entry point for HTML generation using these tools.

Yields:

  • (builder)


34
35
36
37
38
# File 'lib/iron/web/html.rb', line 34

def self.build
  builder = Html.new
  yield builder if block_given?
  builder.render.html_safe
end

.escape_javascript(js) ⇒ Object

And again, thanks Rails team!



66
67
68
69
70
71
72
73
# File 'lib/iron/web/html.rb', line 66

def self.escape_javascript(js)
  if js
    res = js.gsub(/(\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u) {|special| JS_ESCAPE[special] }
    js.html_safe? ? res.html_safe : res
  else
    ''
  end
end

.escape_once(html) ⇒ Object

The escape methods #escape_once and #escape_javascript are both taken from Rails, which like this library is MIT licensed. The following license statement applies to those two methods and the constants they reference. Thanks Rails team!

Copyright © 2004-2013 David Heinemeier Hansson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Ripped from Rails…



60
61
62
63
# File 'lib/iron/web/html.rb', line 60

def self.escape_once(html)
  return html if html.html_safe?
  html.to_s.gsub(/[\"><]|&(?!([a-zA-Z]+|(#\d+));)/) { |special| HTML_ESCAPE[special] }.html_safe
end

Instance Method Details

#<<(new_item) ⇒ Object

Allow pushing new elements



97
98
99
100
101
102
103
104
# File 'lib/iron/web/html.rb', line 97

def <<(new_item)
  if @item_stack.empty?
    @items << new_item
  else
    @item_stack.last.html << new_item
  end
  self
end

#blank?Boolean



119
120
121
# File 'lib/iron/web/html.rb', line 119

def blank?
  empty?
end

#comment!(str) ⇒ Object

Inserts an HTML comment (eg <!– yo –>)



83
84
85
86
87
88
89
# File 'lib/iron/web/html.rb', line 83

def comment!(str)
  if str.include? "\n"
    text! "<!--\n#{str}\n-->\n"
  else
    text! "<!-- #{str} -->\n"
  end
end

#countObject



111
112
113
# File 'lib/iron/web/html.rb', line 111

def count
  @items.count
end

#eachObject

Implement enumerable



107
108
109
# File 'lib/iron/web/html.rb', line 107

def each
  @items.each {|v| yield v} if block_given?
end

#empty?Boolean



115
116
117
# File 'lib/iron/web/html.rb', line 115

def empty?
  @items.empty?
end

#inspectObject

Alias for #render



183
184
185
# File 'lib/iron/web/html.rb', line 183

def inspect
  render
end

#is_a?(other) ⇒ Boolean



187
188
189
# File 'lib/iron/web/html.rb', line 187

def is_a?(other)
  return other == Html
end

#render(depth = 0, inblock = true) ⇒ Object

Renders out as html - accepts depth param to indicate level of indentation



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/iron/web/html.rb', line 159

def render(depth = 0, inblock = true)
  # Convert elements to strings
  @items.collect do |item|
    if item.is_a?(String)
      if inblock
        inblock = false
        '  '*depth + item
      else
        item
      end
    elsif item.nil?
      ''
    else
      item.render(depth,inblock)
    end
  end.join('')
end

#respond_to_missing?(method, include_private) ⇒ Boolean

Make sure our objects advertise their support of tags



149
150
151
152
153
154
155
156
# File 'lib/iron/web/html.rb', line 149

def respond_to_missing?(method, include_private)
  parts = method.to_s.match(/^([a-z]+[0-9]?)$/)
  if parts
    true
  else
    super
  end
end

#tag(tag, *args, &block) ⇒ Object

Create a new element explicitly



124
125
126
127
128
129
130
131
132
133
# File 'lib/iron/web/html.rb', line 124

def tag(tag, *args, &block)
  item = Html::Element.new(tag, *args)
  self << item
  if block
    @item_stack.push item
    block.call(item) 
    @item_stack.pop
  end
  return self
end

#text!(str) ⇒ Object

Inserts raw text



92
93
94
# File 'lib/iron/web/html.rb', line 92

def text!(str)
  self << str
end

#to_sObject

Alias for #render



178
179
180
# File 'lib/iron/web/html.rb', line 178

def to_s
  render
end