Module: Eclair

Extended by:
T::Helpers, T::Sig
Defined in:
lib/eclair.rb,
lib/eclair/html.rb,
lib/eclair/element.rb

Defined Under Namespace

Modules: Html Classes: Element

Class Method Summary collapse

Class Method Details

.element(tag, attributes, children) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/eclair.rb', line 21

def self.element(tag, attributes, children)
  Element.new(
    tag: tag,
    attributes: attributes,
    children: children
  )
end

.render(element) ⇒ Object



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
71
72
73
74
75
76
77
# File 'lib/eclair.rb', line 30

def self.render(element)
  attributes = element
    .attributes
    .map do |key, value|
      if !value
        next
      end

      attr_name = escape_html(key.to_s)
      rendered_value = case value
      when TrueClass
        next attr_name
      when String
        escape_html(value)
      else
        T.absurd(value)
      end

      "#{attr_name}=\"#{rendered_value}\""
    end
    .compact
    .join(" ")

  start_tag_open = if attributes.empty?
    "<#{element.tag}"
  else
    "<#{element.tag} #{attributes}"
  end

  if (c = element.children) == Element::Void
    return "#{start_tag_open}>"
  end

  rendered_children = c.map do |child|
    case child
    when Element
      render(child)
    when Element::DangerousUnescapedHtml
      child.html
    when String
      escape_html(child)
    else
      T.absurd(child)
    end
  end

  "#{start_tag_open}>#{rendered_children.join}</#{element.tag}>"
end