Class: Spree::Emails::TranslationInliner

Inherits:
Object
  • Object
show all
Defined in:
app/services/spree/emails/translation_inliner.rb

Overview

Turns Spree's translation keys in a template into readable text in one language, for a merchant who starts editing it:

{{ 'order_mailer.confirm_email.dear_customer' | t: name: order.customer_name }}
# => Dear {{ order.customer_name }},

{% assign heading = 'order_mailer.confirm_email.order_summary' | t: number: order.number %}
# => {% capture heading %}Order {{ order.number }} Summary{% endcapture %}

A use it cannot turn into text exactly (a plural form, a missing translation, a value it does not recognize) is left as it was, so the template still renders the same.

Constant Summary collapse

OUTPUT_TAG =

Tags are found with simple patterns and read with string handling, so matching stays linear on any input a merchant pastes in.

/\{\{([^{}]*)\}\}/
ASSIGN_TAG =
/\{%([^{}%]*)%\}/
TRANSLATED =
/\A'([a-z0-9_.]+)'\s*\|\s*t\b/
ASSIGNED =
/\Aassign\s+(\w+)\s*=\s*/
INTERPOLATION =
/%\{(\w+)\}/

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(locale, escape = true) ⇒ TranslationInliner

Returns a new instance of TranslationInliner.



33
34
35
36
# File 'app/services/spree/emails/translation_inliner.rb', line 33

def initialize(locale, escape = true)
  @locale = locale
  @escape = escape
end

Class Method Details

.call(source, locale:, escape: true) ⇒ String?

Parameters:

  • source (String, nil) —

    a template's subject or body

  • locale (String, Symbol) —

    the language to write the text in

  • escape (Boolean) (defaults to: true) —

    whether the text is HTML: false for a subject, which renders unescaped as a mail header

Returns:

  • (String, nil)


29
30
31
# File 'app/services/spree/emails/translation_inliner.rb', line 29

def self.call(source, locale:, escape: true)
  new(locale, escape).call(source)
end

Instance Method Details

#call(source) ⇒ Object



38
39
40
41
42
43
44
# File 'app/services/spree/emails/translation_inliner.rb', line 38

def call(source)
  return source if source.blank?

  source.
    gsub(ASSIGN_TAG) { |tag| inline_assign(markup(Regexp.last_match[1])) || tag }.
    gsub(OUTPUT_TAG) { |tag| inline_output(markup(Regexp.last_match[1])) || tag }
end