Sha256: 0192b246c28e0c4a1cfd227e8b6cb2c8868e994079000f6b34f35291a6111c1f

Contents?: true

Size: 1.78 KB

Versions: 5

Compression:

Stored size: 1.78 KB

Contents

module EffectiveEmailTemplates
  class Importer
    def self.import(quiet: false, paths: nil)
      new().execute(overwrite: false, paths: paths, quiet: quiet)
    end

    def self.overwrite(quiet: false, paths: nil)
      new().execute(overwrite: true, paths: paths, quiet: quiet)
    end

    def execute(overwrite:, paths: nil, quiet: false)
      return false unless ActiveRecord::Base.connection.table_exists?(EffectiveEmailTemplates.email_templates_table_name)

      paths ||= ActionController::Base.view_paths.map(&:path)

      paths.each do |path|
        Dir[Rails.root.join(path, '**', '*_mailer/', '*.liquid')].each do |filepath|
          name = File.basename(filepath, '.liquid')
          email_template = Effective::EmailTemplate.find_or_initialize_by(template_name: name)

          if email_template.persisted? && !overwrite
            puts("SKIPPED #{filename(filepath)}") unless quiet
            next
          end

          save(email_template, filepath, quiet: quiet)
        end
      end
    end

    private

    def save(email_template, filepath, quiet:)
      file = File.new(filepath, 'r')

      attributes = begin
        content = YAML.load(file)
        content.kind_of?(Hash) ? content : {}
      end

      body = File.open(file) do |f|
        content = f.read
        match = content.match(/(---+(.|\n)+---+)/)
        content.gsub(match[1], '').strip if match
      end

      email_template.assign_attributes(attributes)
      email_template.assign_attributes(body: body)

      if email_template.save
        puts("SUCCESS #{filename(filepath)}") unless quiet
      else
        puts "ERROR #{filename(filepath)}: #{email_template.errors.full_messages.to_sentence}"
      end
    end

    def filename(filepath)
      filepath.sub(Rails.root.to_s + '/app/', '')
    end

  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
effective_email_templates-1.2.0 lib/effective_email_templates/importer.rb
effective_email_templates-1.1.4 lib/effective_email_templates/importer.rb
effective_email_templates-1.1.3 lib/effective_email_templates/importer.rb
effective_email_templates-1.1.2 lib/effective_email_templates/importer.rb
effective_email_templates-1.1.1 lib/effective_email_templates/importer.rb