Module: TextHelpers::Translation

Defined in:
lib/text_helpers/translation.rb

Constant Summary collapse

ORPHAN_MATCHER =
/(\w+)[ \t](?![^<]*>)(\S+\s*<\/(?:p|li)>)/.freeze
KEYPATH_MATCHER =
/!([\w.\/]+)!/.freeze

Instance Method Summary collapse

Instance Method Details

#html(key, options = {}) ⇒ Object

Public: Get an HTML representation of the rendered markdown for the passed I18n key.

key - The desired I18n lookup key. options - A Hash of options to pass through to the lookup.

:inline  - A special option that will remove the enclosing <p>
           tags when set to true.
:orphans - A special option that will prevent the insertion of
           non-breaking space characters at the end of each
           paragraph when set to true.

Returns a String containing the localized text rendered via Markdown



66
67
68
69
70
71
72
# File 'lib/text_helpers/translation.rb', line 66

def html(key, options = {})
  rendered = markdown(text(key, options.merge(smart: false)))

  rendered = options[:orphans] ? rendered : rendered.gsub(ORPHAN_MATCHER, '\1&nbsp;\2')
  rendered = rendered.gsub(/<\/?p>/, '') if options[:inline]
  rendered.html_safe
end

#text(key, options = {}) ⇒ Object

Public: Get the I18n localized text for the passed key.

key - The desired I18n lookup key. options - A Hash of options to forward to the ‘I18n.t` lookup.

:smart - Whether or not to apply smart quoting to the output.
         Defaults to true.

Returns a String resulting from the I18n lookup.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/text_helpers/translation.rb', line 36

def text(key, options = {})
  options = html_safe_options(options)
  text = I18n.t(key, **{
    scope: self.translation_scope,
    default: "!#{key}!",
    cascade: true,
  }.merge(options)).strip

  interpolation_options = { cascade: true }.merge(options)

  # Interpolate any keypaths (e.g., `!some.lookup.path/key!`) found in the text.
  while text.match?(KEYPATH_MATCHER) do
    text = text.gsub(KEYPATH_MATCHER) { |match| I18n.t($1, **interpolation_options) }
  end

  text = smartify(text) if options.fetch(:smart, true)
  text.html_safe
end