Sha256: 4413c3f257e91ad6da5085290b4902c9ca1ff4e2af5cab39e51679b978970547

Contents?: true

Size: 1.37 KB

Versions: 3

Compression:

Stored size: 1.37 KB

Contents

module EffectiveEmailTemplates
  class TemplateImporter
    def self.invoke(importer = new)
      importer.invoke
    end

    def invoke
      Dir[Rails.root.join('app', 'views', '**', '*.liquid')].each do |liquid_template_filepath|
        slug = File.basename(liquid_template_filepath, '.liquid')
        next if Effective::EmailTemplate.where(slug: slug).present?

        template = Effective::EmailTemplate.new(slug: slug)

        file = File.new(liquid_template_filepath, "r")
        template = add_template_meta(file, template)
        template.body = extract_template_body(file)
        template.save
        print_errors(template, liquid_template_filepath) unless template.valid?
      end
    end

  private

    def add_template_meta(file, template)
      template.attributes = File.open(file) do |f|
        attr = YAML::load(f)
        attr.is_a?(Hash) ? attr : {}
      end
      template
    end

    def extract_template_body file
      contents = file.read
      return unless match = contents.match(/(---+(.|\n)+---+)/)
      contents.gsub(match[1], '').strip
    end

    def print_errors(template, liquid_template_filepath)
      puts "ERROR -- There was one or more validation errors while uploading:"
      puts "  Email Template: #{liquid_template_filepath}"
      template.errors.each do |attribute, error|
        puts "  -> #{attribute} #{error}"
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
effective_email_templates-0.3.1 lib/effective_email_templates/template_importer.rb
effective_email_templates-0.3.0 lib/effective_email_templates/template_importer.rb
effective_email_templates-0.2.8 lib/effective_email_templates/template_importer.rb