Module: SafeFormatHelper

Included in:
Emails::Profile, EmailsHelper
Defined in:
app/helpers/safe_format_helper.rb

Instance Method Summary collapse

Instance Method Details

#safe_format(format, *args) ⇒ Object

Returns a HTML-safe String.

Examples:

safe_format('See %{user_input}', user_input: '<b>bold</b>')
# => "See &lt;b&gt;bold&lt;/b&gt"

safe_format('In &lt; hour & more')
# => "In &lt; hour &amp; more"

With tag_pair support

safe_format('Some %{open}bold%{close} text.', tag_pair(tag.strong, :open, :close))
# => "Some <strong>bold</strong> text."
safe_format('Some %{open}bold%{close} %{italicStart}text%{italicEnd}.',
  tag_pair(tag.strong, :open, :close),
  tag_pair(tag.i, :italicStart, :italicEnd))
# => "Some <strong>bold</strong> <i>text</i>.

Parameters:

  • format (String)

    is escaped via ‘html_escape_once`

  • args (Array<Hash>)

    are escaped via ‘html_escape` if they are not marked as HTML-safe



23
24
25
26
27
28
29
30
31
# File 'app/helpers/safe_format_helper.rb', line 23

def safe_format(format, *args)
  args = args.inject({}, &:merge)

  # Use `Kernel.format` to avoid conflicts with ViewComponent's `format`.
  Kernel.format(
    html_escape_once(format),
    args.transform_values { |value| html_escape(value) }
  ).html_safe
end

#tag_pair(html_tag, open_name, close_name) ⇒ Object

Returns a Hash containing a pair of open and close tag parts extracted from HTML-safe tag. The values are HTML-safe.

Returns an empty Hash if tag is not a valid paired tag (e.g. <p>foo</p>). an empty Hash is returned.

Examples:

tag_pair(tag.strong, :open, :close)
# => { open: '<strong>', close: '</strong>' }
tag_pair(link_to('', '/'), :open, :close)
# => { open: '<a href="/">', close: '</a>' }

Parameters:

  • html_tag (String)

    is a HTML-safe output from tag helper

  • open_name (Symbol, Object)

    name of opening tag

  • close_name (Symbol, Object)

    name of closing tag

Raises:

  • (ArgumentError)

    if tag is not HTML-safe



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'app/helpers/safe_format_helper.rb', line 49

def tag_pair(html_tag, open_name, close_name)
  raise ArgumentError, 'Argument `tag` must be `html_safe`!' unless html_tag.html_safe?
  return {} unless html_tag.start_with?('<')

  # end of opening tag: <p>foo</p>
  #                       ^
  open_index = html_tag.index('>')
  # start of closing tag: <p>foo</p>
  #                             ^^
  close_index = html_tag.rindex('</')

  return {} unless open_index && close_index

  {
    open_name => html_tag[0, open_index + 1],
    close_name => html_tag[close_index, html_tag.size]
  }
end