3

ActiveJob用来发送邮件:

使用deliver_now方法:

invoices_controller.rb

def send_invoice
  #other stuff
  Members::InvoicesMailer.send_invoice(@invoice.id, view_context).deliver_now
end

invoices_mailer.rb

require 'open-uri'
class Members::InvoicesMailer < ApplicationMailer
  def send_invoice(invoice_id, view_context)
    @invoice = Invoice.find(invoice_id)
    attachments["#{@invoice.identifier}.pdf"] = InvoicePdf.new(@invoice, view_context).render

    mail :to => @invoice.client.email, :subject => "Invoice"
  end
end

请注意,我正在将view_context控制器从控制器发送到邮件程序,这将再次将其传递给InvoicePdf类以生成发票。

结果:电子邮件发送正确

使用deliver_later方法:

invoices_controller.rb

def send_invoice
  #other stuff
  Members::InvoicesMailer.send_invoice(@invoice.id, view_context).deliver_later
end

结果: ActiveJob::SerializationError in Members::InvoicesController#send_invoice Unsupported argument type: view_context

如何注入view_context内部InvoicePdf,或者从内部加载InvoicePdf,或者InvoiceMailer

编辑:这就是 InvoicePdf 的样子

invoice_pdf.rb

class InvoicePdf < Prawn::Document
  def initialize(invoice, view_context)
    @invoice, @view_context = invoice, view_context
    generate_pdf
  end

  def generate_pdf
    # calling some active_support helpers:
      # @view_context.number_to_currency(//)
    # calling some helpers I created
  end
end
4

1 回答 1

3

传递像视图上下文这样的对象然后使用的问题deliver_later是,您给它的参数被序列化到某个后端(redis、MySQL),然后另一个ruby​​ 后台进程将其拾取。

像视图上下文这样的对象并不是你可以序列化的东西。这不是真正的数据

您可以只使用ActionView::Base.new,例如来自rails console

# New ActionView::Base instance
vagrant :002 > view = ActionView::Base.new

# Include some helper classes
vagrant :003 > view.class_eval { include ApplicationHelper }
vagrant :004 > view.class_eval { include Rails.application.routes.url_helpers }

# Now you can run helpers from `ApplicationHelper`
vagrant :005 > view.page_title 'Test' 
"Test"

# And from url_helpers
vagrant :006 > view.link_to 'Title', [:admin, :organisations]
 => "<a href=\"/admin/organisations\">Title</a>" 

这是我在PdfMaker课堂上所做的,可能与您的InvoicePdf课堂相似。

    def action_view
        @action_view ||= begin
            view = ActionView::Base.new ActionController::Base.view_paths

            view.class_eval do
                include Rails.application.routes.url_helpers
                include ApplicationHelper
                include FontAwesome::Rails::IconHelper
                include Pundit

                def self.helper_method *name; end
                def view_context; self; end
                def self.before_action f; end
                def protect_against_forgery?; end
            end

            view
        end
    end
于 2015-05-03T18:41:06.017 回答