Sha256: 644514357c8c9884f51285d7d466dfc764c45fe905a75fd0835cd20508d9ad89

Contents?: true

Size: 1.98 KB

Versions: 2

Compression:

Stored size: 1.98 KB

Contents

# sugessted usage
# Mailer.deliver(:confirm_email, 'rejotl@gmailcom')
# Mailer.render(:confirm_email, 'rejotl@gmailcom')

# natively works like
# Mailer.prepare(:confirm_email, 'rejotl@gmailcom').deliver
# Mailer.prepare(:confirm_email, 'rejotl@gmailcom').body

# Rails mode via method missing is suported
# Mailer.confirm_email('rejotl@gmailcom').deliver
# Mailer.confirm_email('rejotl@gmailcom').body

class Lux::Mailer
  ClassCallbacks.define self, :before, :after
  class_attribute :helper

  attr_reader :mail

  class << self
    # Mailer.prepare(:confirm_email, 'rejotl@gmailcom')
    def prepare template, *args
      obj = new
      obj.instance_variable_set :@_template, template

      ClassCallbacks.execute obj, :before
      obj.send template, *args
      ClassCallbacks.execute obj, :after

      obj
    end

    def render method_name, *args
      send(method_name, *args).body
    end

    def method_missing method_sym, *args
      prepare(method_sym, *args)
    end

    def deliver
      send(method_name, *args).deliver
    end
  end

  ###

  def initialize
    @mail = DynamicClass.new subject: nil, body: nil, to: nil, cc: nil, from: nil
  end

  def deliver
    raise "From in mailer not defined"    unless @mail.from
    raise "To in mailer not defined"      unless @mail.to
    raise "Subject in mailer not defined" unless @mail.subject

    require 'mail'

    Mail.defaults { delivery_method Lux.config(:mail).delivery, Lux.config(:mail).opts }

    m = Mail.new
    m[:from]         = @mail.from
    m[:to]           = @mail.to
    m[:subject]      = @mail.subject
    m[:body]         = @mail.body || body
    m[:content_type] = 'text/html; charset=UTF-8'

    Thread.new { m.deliver! }
  end

  def deliver_later
     Lux.delay self, :deliver
  end

  def body
    return @mail.body if @mail.body

    helper = Lux::Helper.new self, self.class.helper

    Lux::Template.render_with_layout "mailer/#{@_template}", helper
  end

  def subject
    @mail.subject
  end

  def to
    @mail.to
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
lux-fw-0.2.3 ./lib/lux/mailer/mailer.rb
lux-fw-0.2.1 ./lib/lux/mailer/mailer.rb