custom_emails 0.0.1 → 0.0.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -10,11 +10,13 @@ if defined?(ActionMailer)
10
10
  end
11
11
 
12
12
  def email_to(email, dest, options={})
13
- sender = options[:from] || CustomEmails.default_from
13
+ context = options[:context] || {}
14
+ sender = options[:from] || CustomEmails.default_from
15
+ subject = email.interpolated_subject(context)
14
16
 
15
- mail(to: dest, from: sender, subject: email.subject) do |format|
16
- format.html { email.content_html } unless email.content_html.blank?
17
- format.text { email.content_text }
17
+ mail(to: dest, from: sender, subject: subject) do |format|
18
+ format.html { email.interpolated_content_html(context) } if email.content_html.present?
19
+ format.text { email.interpolated_content_text(context) }
18
20
  end
19
21
  end
20
22
  end
@@ -1,3 +1,5 @@
1
+ require 'liquid'
2
+
1
3
  module CustomEmails
2
4
  class Email < ActiveRecord::Base
3
5
  if CustomEmails.scoped
@@ -7,9 +9,52 @@ module CustomEmails
7
9
  belongs_to :kind, class_name: EmailKind, inverse_of: :emails
8
10
 
9
11
  validates_presence_of :locale, :subject, :content_text, :kind
12
+ validate :ensure_valid_templates
10
13
 
11
- def to(dest, options={})
14
+ def to(dest, context={}, options={})
15
+ options[:context] ||= context
12
16
  CustomEmails::Mailer.email_to(self, dest, options)
13
17
  end
18
+
19
+ # Create an interpolated version of some attributes
20
+ %w(subject content_text content_html).each do |attr|
21
+ class_eval "def interpolated_#{attr}(context) ; interpolate(#{attr}, context) end"
22
+ end
23
+
24
+ # Checks if a content is valid for interpolation.
25
+ #
26
+ # @return [Boolean]
27
+ def self.valid_template?(content)
28
+ return true if content.blank?
29
+
30
+ template = ::Liquid::Template.parse(content)
31
+ template.errors.empty?
32
+ end
33
+
34
+ private
35
+
36
+ # Use liquid to get the result of template interpretation.
37
+ #
38
+ # @param [String] the template
39
+ # @param [Hash] the variable tree that have to be inserted into the template
40
+ # @retrun [String]
41
+ def interpolate(content, context)
42
+ template = ::Liquid::Template.parse(content)
43
+ if template.errors.empty?
44
+ template.render(context)
45
+ else
46
+ content
47
+ end
48
+ end
49
+
50
+ def ensure_valid_templates
51
+ if content_text.present? && !self.class.valid_template?(content_text)
52
+ errors.add(:content_text, 'errors are found in the content_text template')
53
+ end
54
+
55
+ if content_html.present? && !self.class.valid_template?(content_html)
56
+ errors.add(:content_html, 'errors are found in the content_html template')
57
+ end
58
+ end
14
59
  end
15
60
  end
@@ -1,3 +1,3 @@
1
1
  module CustomEmails
2
- VERSION = "0.0.1"
2
+ VERSION = "0.0.2"
3
3
  end