module Hdh::Helpers

Constants

VOID_ELEMENTS

Public Instance Methods

html(h)
Alias for: render
render(h) click to toggle source
# File lib/hdh/helpers.rb, line 2
def render(h)
  return escape(h) unless h.is_a?(Array)

  h.any? ? render_tag(h) : ''
end
Also aliased as: html

Private Instance Methods

escape(s) click to toggle source
# File lib/hdh/helpers.rb, line 55
def escape(s)
  case s
  when String then s
  else s.to_s
  end
end
parse_shorthands(tag_name, attrs) click to toggle source
# File lib/hdh/helpers.rb, line 28
def parse_shorthands(tag_name, attrs)
  attrs = attrs&.dup || {}
  tid, *cl = tag_name.to_s.split('.')
  t, id, *other_ids = tid.split('#')
  raise ArgumentError, "Invalid HTML tag: #{tag_name}" unless t
  raise ArgumentError, "Invalid HTML tag with multiple ids: #{tag_name}" if other_ids.any?

  attrs[:id] = id if id
  attrs[:class] = Array(attrs[:class]) + cl if cl.any?
  [t || :div, attrs]
end
r() click to toggle source
# File lib/hdh/helpers.rb, line 62
def r
  method(:render)
end
render_tag(h) click to toggle source
# File lib/hdh/helpers.rb, line 14
def render_tag(h)
  t, *cs = h
  attrs, *cs = cs if cs.first.is_a?(Hash)
  t, attrs = parse_shorthands(t, attrs)

  opening = "#{t}#{render_tag_attributes(attrs)}"
  if VOID_ELEMENTS.include?(t.to_sym) ||
     (cs.empty? && t =~ /^[A-Z]/)
    "<#{opening} />"
  else
    "<#{opening}>#{cs.map(&r).join}</#{t}>"
  end
end
render_tag_attributes(attrs, prefix: '') click to toggle source
# File lib/hdh/helpers.rb, line 40
def render_tag_attributes(attrs, prefix: '')
  return '' unless attrs

  attrs.map do |k, v|
    case v
    when Hash
      render_tag_attributes(v, prefix: "#{prefix}#{k}-")
    when Array
      " #{k}=\"#{v.map(&method(:escape)).join(' ')}\""
    else
      " #{k}=\"#{escape(v)}\""
    end
  end.join
end