Sha256: 0079bcccd1fc5618904fa100aafb636e4831c11c90d5509ce15450eaad8f12cc

Contents?: true

Size: 1.92 KB

Versions: 5

Compression:

Stored size: 1.92 KB

Contents

require 'haml'
require 'ditty/components/app'

module Ditty
  module Emails
    class Base
      attr_accessor :options, :locals, :mail

      def initialize(options = {})
        @mail = options[:mail] || Mail.new
        @locals = options[:locals] || {}
        @options = base_options.merge options
      end

      def deliver!(to = nil, locals = {})
        options[:to] = to unless to.nil?
        @locals.merge!(locals)
        %i[to from subject].each do |param|
          mail.send(param, options[param]) if options[param]
        end
        mail.body content
        mail.deliver!
      end

      def method_missing(method, *args, &block)
        return super unless respond_to_missing?(method)
        mail.send(method, *args, &block)
      end

      def respond_to_missing?(method, _include_private = false)
        mail.respond_to? method
      end

      private

      def content
        result = Haml::Engine.new(content_haml).render(Object.new, locals)
        return result unless options[:layout]
        Haml::Engine.new(layout_haml).render(Object.new, content: result)
      end

      def content_haml
        read_template(options[:view])
      end

      def layout_haml
        read_template("layouts/#{options[:layout]}") if options[:layout]
      end

      def read_template(template)
        File.read(find_template("emails/#{template}"))
      end

      def base_options
        { subject: '(No Subject)', from: 'no-reply@ditty.io', view: :base }
      end

      def find_template(file)
        template = File.expand_path("./views/#{file}.haml")
        return template if File.file? template
        template = File.expand_path("./#{file}.haml", App.view_folder)
        return template if File.file? template
        file
      end

      class << self
        def deliver!(to = nil, options = {})
          locals = options[:locals] || {}
          new(options).deliver!(to, locals)
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
ditty-0.7.2 lib/ditty/emails/base.rb
ditty-0.7.1 lib/ditty/emails/base.rb
ditty-0.7.0 lib/ditty/emails/base.rb
ditty-0.7.0.pre.rc1 lib/ditty/emails/base.rb
ditty-0.6.0 lib/ditty/emails/base.rb