Module: DTC::Utils::Text::HTML

Defined in:
lib/dtc/utils/text/html.rb

Defined Under Namespace

Classes: Writer

Constant Summary collapse

ATTRIBUTE_ALIASES =
({})
SHORTFORM_TAGS =
%w[area base basefont br col frame hr img input link meta param]
NOINDENT_TAGS =
%w[pre textarea]

Class Method Summary collapse

Class Method Details

.attributes(attrs = {}) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/dtc/utils/text/html.rb', line 50

def self.attributes attrs = {}
  unless attrs.nil? || attrs.empty?
    " " + (
      attrs.map do |k, v|
        key = (
          ATTRIBUTE_ALIASES[k] ||
          ATTRIBUTE_ALIASES[k.to_s] ||
          k
        ).to_s
        if v == true
          CGI::escapeHTML(key)
        elsif !v
          nil
        else
          "#{CGI::escapeHTML(key)}='#{CGI::escapeHTML(v.is_a?(Array) ? v.join(" ") : v.to_s)}'"
        end
      end).select {|e| e} .join(" ")
  else
    ""
  end
end

.tag(sym, content = :open_close, attrs = {}) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/dtc/utils/text/html.rb', line 74

def self.tag sym, content = :open_close, attrs = {}
  tag = sym.to_s.split(".")
  nature = :open_close
  content = content.join("") if content.is_a?(Array)
  if content.is_a?(Symbol)
    nature = content unless content == :full
  elsif !content.nil? && content.strip != ""
    nature = :full
  else
    nature = SHORTFORM_TAGS.index(tag.first.downcase) ? :short : :open_close
  end
  tag_header = tag_name = tag.first.to_s
  unless (nature = nature.to_sym) == :close
    if tag.count > 1
      attrs ||= {}
      classes = attrs[:class] || []
      classes = classes.split(/\s+/) if classes.is_a?(String)
      classes += tag.drop(1).to_a
      attrs[:class] = classes.uniq
    end
    tag_header += attributes(attrs) unless nature == :close
  end
  natures = ({:open => %w[< >], :close => ['</', '>'], :short => ['<', ' />'], :open_close => ['<', "></#{tag_name}>"]})
  if nature == :full
    natures[:open].join(tag_header) + content + natures[:close].join(tag_name)
  else
    raise RuntimeError, "Unknown tag nature #{nature.inspect}, should be one of #{natures.keys.to_a.inspect}" unless natures[nature]
    natures[nature].join(tag_header)
  end
end