Module: TextHelpers::Translation

Defined in:
lib/text_helpers/translation.rb

Constant Summary collapse

ORPHAN_MATCHER =
/\s(?![^<]*>)(\S+\s*<\/(?:p|li)>)/.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



49
50
51
52
53
54
55
# File 'lib/text_helpers/translation.rb', line 49

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

  rendered = options[:orphans] ? rendered : rendered.gsub(ORPHAN_MATCHER, '&nbsp;\1')
  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.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/text_helpers/translation.rb', line 19

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

  interpolation_options = options.dup
  interpolation_options[:cascade] = true unless interpolation_options.has_key?(:cascade)

  # Interpolate any keypaths (e.g., `!some.lookup.path/key!`) found in the text.
  while text =~ /!([\w._\/]+)!/ do
    text = text.gsub(/!([\w._\/]+)!/) { |match| I18n.t($1, interpolation_options) }
  end

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