Sha256: ca54582d58d2abb433f6b0a04ac7bed559e1a6e1b0d54d195b635568a1cdd3f3

Contents?: true

Size: 1.48 KB

Versions: 17

Compression:

Stored size: 1.48 KB

Contents

require 'liquid'
Liquid::Template.error_mode = :strict # Raises a SyntaxError when invalid syntax is used

module Effective
  class EmailTemplate < ActiveRecord::Base

    self.table_name = EffectiveEmailTemplates.email_templates_table_name.to_s

    serialize :template, Liquid::Template

    validate :slug_needs_to_have_simple_format
    validates :slug,      presence: true, uniqueness: true
    validates :body,      presence: true
    validates :subject,   presence: true
    validates :from,      presence: true
    validates :template,  presence: true

    before_validation :try_precompile

    def precompile
      begin
        self.template = Liquid::Template.parse( body )
      rescue Liquid::SyntaxError => error
        errors.add :template, error.message
      end
    end

    def mail_options
      {
        from: from,
        subject: subject,
        cc: cc,
        bcc: bcc
      }.delete_if { |_, v| v.blank? }
    end

    def render( *args )
      template.render( *args )
    end

  private

    def try_precompile
      precompile if body_changed?
    end

    def slug_needs_to_have_simple_format
      # convert slug to symbol
      # add error if symbol has non-simple format (i.e. `:"symbol with spaces"` vs `:symbol_with_underscores`)
      if /[@$"]/ =~ slug.to_sym.inspect || slug.match(/[A-Z]/)
        errors.add(:slug, 'must have a simple format with no spaces, capital letters, and most punctuation (good: "hello_world", bad: "hello, world")')
      end
    end
  end
end

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
effective_email_templates-0.6.1 app/models/effective/email_template.rb
effective_email_templates-0.6.0 app/models/effective/email_template.rb
effective_email_templates-0.5.1 app/models/effective/email_template.rb
effective_email_templates-0.5.0 app/models/effective/email_template.rb
effective_email_templates-0.4.6 app/models/effective/email_template.rb
effective_email_templates-0.4.5 app/models/effective/email_template.rb
effective_email_templates-0.4.4 app/models/effective/email_template.rb
effective_email_templates-0.4.3 app/models/effective/email_template.rb
effective_email_templates-0.4.2 app/models/effective/email_template.rb
effective_email_templates-0.4.1 app/models/effective/email_template.rb
effective_email_templates-0.4.0 app/models/effective/email_template.rb
effective_email_templates-0.3.5 app/models/effective/email_template.rb
effective_email_templates-0.3.4 app/models/effective/email_template.rb
effective_email_templates-0.3.3 app/models/effective/email_template.rb
effective_email_templates-0.3.1 app/models/effective/email_template.rb
effective_email_templates-0.3.0 app/models/effective/email_template.rb
effective_email_templates-0.2.8 app/models/effective/email_template.rb