Module: Cybertrain::Html

Defined in:
cybertrain/html.rb,
cybertrain/html.rb

Overview

HTML escaping for controllers and models. Templates escape <%= %> output themselves; these are for building HTML in Ruby, e.g. for render html:.

Defined Under Namespace

Classes: TagBuilder

Constant Summary collapse

VOID_ELEMENTS =

Elements that have no content and no closing tag.

%w[area base br col embed hr img input link meta source track wbr]
TAG_BUILDER =
TagBuilder.new

Class Method Summary collapse

Class Method Details

.class_names(*values) ⇒ String

Rails’ class_names / token_list: the words of Strings and Symbols, of Arrays (nested too) and of each Hash key whose value is truthy, each word once, in order. class_names("a", { "b" => true, "c" => false }) is “a b”.

Returns:

  • (String)


385
386
387
# File 'cybertrain/html.rb', line 385

def self.class_names(*values)
  class_names_of(values)
end

.dom_id(record, prefix = "") ⇒ String

The DOM id Rails’ dom_id gives a record: “article_12”, “new_article” for one without an id yet, “edit_article_12” with a prefix. The record answers model_name and id (a Cybertrain::Model does); as in Rails the id decides, not whether the record is saved, so a record built with an id (set_id) names the element the page rendered for it. No id is 0 (a Model’s) or nil (another record-like object’s).

Parameters:

  • prefix (String) (defaults to: "") —

    ”” for none

Returns:

  • (String)


436
437
438
439
440
441
442
443
444
# File 'cybertrain/html.rb', line 436

def self.dom_id(record, prefix = "")
  key = Inflector.underscore(record.model_name).tr("/", "_")
  id = record.id
  if id.nil? || id == 0
    return prefix.empty? ? "new_#{key}" : "#{prefix}_#{key}"
  end

  prefix.empty? ? "#{key}_#{id}" : "#{prefix}_#{key}_#{id}"
end

.escape(value) ⇒ String

Escapes the five characters that matter for HTML text/attribute contexts. Scans bytes (the five are ASCII, so multibyte UTF-8 sequences are never split) and returns the input untouched when nothing needs escaping, since most interpolated values are plain text. Measured 2.7x faster than an each_char loop under Spinel; this runs for every <%= %>.

&, <, >, " and ' become entities.

Parameters:

  • value (String)

Returns:

  • (String)


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'cybertrain/html.rb', line 22

def self.escape(value)
  # The parameter is polymorphic under Spinel (callers hand in Strings of
  # more than one static type), which made every getbyte and comparison
  # below a dynamic call: most of this method's time. value.to_s has one
  # static type (every to_s in the program returns a String; SafeString's
  # included, see SafeString::EMPTY), so the loops compile to plain
  # C, and for a String it is the String itself, not a copy. It is also
  # what comes back when nothing needs escaping, so callers get a typed
  # String rather than the polymorphic parameter. Spinel 2026.09.12
  # narrowed a parameter used only through to_s to one caller's type (it
  # once inferred an Integer here and turned Strings into "0"), so this
  # used to be a `case value when String`; that no longer happens on
  # 2026.10.27.7020 (docs/spinel-feedback.md, item 2).
  str = value.to_s
  n = str.bytesize
  i = 0
  # Most values need nothing: find the first byte that does before
  # allocating a buffer at all.
  while i < n
    b = str.getbyte(i)
    break if b == 38 || b == 60 || b == 62 || b == 34 || b == 39
    i += 1
  end
  return str if i == n

  buf = +""
  dirty = false
  start = 0
  while i < n
    b = str.getbyte(i)
    if b == 38 || b == 60 || b == 62 || b == 34 || b == 39
      buf << str.byteslice(start, i - start) if i > start
      case b
      when 38 then buf << "&amp;"
      when 60 then buf << "&lt;"
      when 62 then buf << "&gt;"
      when 34 then buf << "&quot;"
      else buf << "&#39;"
      end
      start = i + 1
      dirty = true
    end
    i += 1
  end
  return str unless dirty

  buf << str.byteslice(start, n - start) if n > start
  buf
end

.safe(str) ⇒ SafeString

Marks trusted HTML as safe, so it is output as it is.

Examples:

render html: Cybertrain::Html.safe("<p>#{Cybertrain::Html.escape(@article.title)}</p>")

Parameters:

  • str (String)

Returns:



78
79
80
# File 'cybertrain/html.rb', line 78

def self.safe(str)
  SafeString.of(str)
end

.safe_join(items, sep = "") ⇒ SafeString

Joins items into HTML, escaping every item (and the separator) that is not a SafeString: safe_join([tag.b("a"), "<"], " ").

Parameters:

  • items (Array)
  • sep (String, SafeString) (defaults to: "")

Returns:



371
372
373
374
375
376
377
# File 'cybertrain/html.rb', line 371

def self.safe_join(items, sep = "")
  glue = content_html(sep)
  parts = Array.new(0) { "" }
  items.each { |item| parts << content_html(item) }
  joined = parts.join(glue)
  SafeString.of(joined)
end

.tag(name, attrs = {}, content = nil, &block) ⇒ SafeString

An element: Html.tag("a", { href: "/x", class: ["btn", "big"] }, "Go") is <a href="/x" class="btn big">Go</a>. The block’s value, when given, is the content instead of content. Content that is not a SafeString is escaped; a void element (br, input, …) takes none. Attributes: nil and false drop the attribute, true writes it bare (disabled), an Array joins its non-nil items with spaces, data: and aria: Hashes become data-* / aria-* attributes (underscores become dashes, true/false are written out), and every value is escaped, a SafeString too.

Parameters:

  • name (String) —

    the element name, [a-z][a-z0-9-]*

  • attrs (Hash{String, Symbol => Object}) (defaults to: {})
  • content (Object, nil) (defaults to: nil)

Returns:

Raises:

  • (ArgumentError) —

    for an invalid element or attribute name

  • (RuntimeError) —

    for content in a void element



200
201
202
203
204
205
206
207
208
209
210
211
# File 'cybertrain/html.rb', line 200

def self.tag(name, attrs = {}, content = nil, &block)
  inner = ""
  given = false
  if block
    inner = content_html(block.call)
    given = true
  elsif !content.nil?
    inner = content_html(content)
    given = true
  end
  build_tag(name, attrs, inner, given)
end

.tag_attributes(attrs) ⇒ String

The attributes of Html.tag as HTML, each with its leading space (“” for none). Not named attributes: Model#attributes returns a Hash, and one name with two return types corrupts inference (spikes/NOTES.md rule 34).

Parameters:

  • attrs (Hash{String, Symbol => Object})

Returns:

  • (String)


235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'cybertrain/html.rb', line 235

def self.tag_attributes(attrs)
  buf = +""
  # each_key: iterating a Hash of mixed keys into a String sink can box
  # the key (spikes/NOTES.md rule 29).
  attrs.each_key do |key|
    attr_name = key_text(key)
    value = attrs[key]
    nested = false
    if attr_name == "data" || attr_name == "aria"
      case value
      when Hash
        nested = true
        value.each_key do |sub|
          sub_name = "#{attr_name}-#{key_text(sub).tr("_", "-")}"
          buf << attribute_html(sub_name, value[sub], true)
        end
      end
    end
    if !nested && attr_name == "class"
      # class: { active: on } / ["btn", { big: x }]: Rails' class_names.
      case value
      when Time then nil
      when Array, Hash
        nested = true
        list = []
        list << value
        words = class_names_of(list)
        buf << attribute_html(attr_name, words, false)
      end
    end
    buf << attribute_html(attr_name, value, false) unless nested
  end
  buf
end