Module: Eggshell::BlockHandler::HtmlUtils

Overview

Useful methods for generating HTML tags

Constant Summary collapse

HASH_HTML_ESCAPE =
{
  "'" => ''',
  '"' => '"',
  '<' => '&lt;',
  '>' => '&gt;',
  '&' => '&amp;'
}.freeze

Instance Method Summary collapse

Instance Method Details

#attrib_string(map, keys = nil) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/eggshell/block-handler.rb', line 177

def attrib_string(map, keys = nil)
  keys = map.keys if !keys
  buff = []
  keys.each do |key|
    val = map[key]
    if val.is_a?(Hash)
      buff << attrib_string(val)
    elsif val && key[0] != '@'
      buff << " #{key}='#{html_escape(val)}'"
    end
  end
  buff.join()
end

#create_tag(tag, attribs, open = true, body = nil) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/eggshell/block-handler.rb', line 154

def create_tag(tag, attribs, open = true, body = nil)
  str_attribs = ''
  if attribs.is_a?(String)
    str_attribs = attribs
  else
    nattribs = attribs.is_a?(Hash) ? attribs.clone : {}
    if nattribs[BlockParams::STYLE].is_a?(Hash)
      nattribs[BlockParams::STYLE] = css_string(nattribs[BlockParams::STYLE])
    end
    str_attribs = attrib_string(nattribs, BlockParams::KEYS)
  end

  if !open
    return "<#{tag}#{str_attribs}/>"
  else
    if body
      return "<#{tag}#{str_attribs}>#{body}</#{tag}>"
    else
      return "<#{tag}#{str_attribs}>"
    end
  end
end

#css_string(map) ⇒ Object



191
192
193
194
195
196
197
# File 'lib/eggshell/block-handler.rb', line 191

def css_string(map)
  css = []
  map.each do |s,v|
    css << "#{s}: #{html_escape(v)};"
  end
  css.join(' ')
end

#html_escape(str) ⇒ Object



208
209
210
# File 'lib/eggshell/block-handler.rb', line 208

def html_escape(str)
  return str.gsub(/("|'|<|>|&)/, HASH_HTML_ESCAPE)
end