Module: Temple::Utils

Extended by:
Utils
Included in:
Filter, Generator, Parser, Utils
Defined in:
lib/temple/utils.rb

Constant Summary collapse

ESCAPE_HTML =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Used by escape_html

{
  '&'  => '&',
  '"'  => '"',
  '\'' => ''',
  '<'  => '&lt;',
  '>'  => '&gt;'
}.freeze
ESCAPE_HTML_PATTERN =
Regexp.union(*ESCAPE_HTML.keys)

Instance Method Summary collapse

Instance Method Details

#empty_exp?(exp) ⇒ Boolean

Check if expression is empty

Parameters:

  • exp (Array)

    Temple expression

Returns:

  • (Boolean)

    true if expression is empty



66
67
68
69
70
71
72
73
74
75
# File 'lib/temple/utils.rb', line 66

def empty_exp?(exp)
  case exp[0]
  when :multi
    exp[1..-1].all? {|e| empty_exp?(e) }
  when :newline
    true
  else
    false
  end
end

#escape_html(html) ⇒ String

Returns an escaped copy of ‘html`.

Parameters:

  • html (String)

    The string to escape

Returns:

  • (String)

    The escaped string



27
28
29
# File 'lib/temple/utils.rb', line 27

def escape_html(html)
  CGI.escapeHTML(html.to_s)
end

#escape_html_safe(html) ⇒ String

Returns an escaped copy of ‘html`. Strings which are declared as html_safe are not escaped.

Parameters:

  • html (String)

    The string to escape

Returns:

  • (String)

    The escaped string



17
18
19
20
# File 'lib/temple/utils.rb', line 17

def escape_html_safe(html)
  s = html.to_s
  s.html_safe? || html.html_safe? ? s : escape_html(s)
end

#indent_dynamic(text, indent_next, indent, pre_tags = nil) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/temple/utils.rb', line 77

def indent_dynamic(text, indent_next, indent, pre_tags = nil)
  text = text.to_s
  safe = text.respond_to?(:html_safe?) && text.html_safe?
  return text if pre_tags && text =~ pre_tags

  level = text.scan(/^\s*/).map(&:size).min
  text = text.gsub(/(?!\A)^\s{#{level}}/, '') if level > 0

  text = text.sub(/\A\s*\n?/, "\n".freeze) if indent_next
  text = text.gsub("\n".freeze, indent)

  safe ? text.html_safe : text
end

#unique_name(prefix = nil) ⇒ String

Generate unique variable name

Parameters:

  • prefix (String) (defaults to: nil)

    Variable name prefix

Returns:



56
57
58
59
60
# File 'lib/temple/utils.rb', line 56

def unique_name(prefix = nil)
  @unique_name ||= 0
  prefix ||= (@unique_prefix ||= self.class.name.gsub('::'.freeze, '_'.freeze).downcase)
  "_#{prefix}#{@unique_name += 1}"
end