【问题标题】:Rails/Prawn: how do I use rails helpers inside a Prawn class?Rails/Prawn:如何在 Prawn 类中使用 rails 助手?
【发布时间】:2012-03-14 19:32:37
【问题描述】:

我正在尝试在 prawn 类中使用 rails 3.2 助手,但 rails 抛出:

undefined method `number_with_precision' for #<QuotePdf:0x83d4188>

虾类

class QuotePdf < Prawn::Document
  def initialize(quote)
    super()

    text "sum: #{number_with_precision(quote.sum)}"
  end
end

控制器

def show
  @quote = current_user.company.quotes.where(:id => params[:id]).first
  head :unauthorized and return unless @quote

  respond_with @quote, :layout => !params[:_pjax] do |format|
    format.pdf do
      send_data QuotePdf.new(@quote).render, filename: "Devis-#{@quote.date_emission.strftime("%d/%m/%Y")}.pdf",
      type: "application/pdf"
    end
  end
end

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails ruby pdf prawn


    【解决方案1】:

    您必须在对虾文档类中明确包含ActionView::Helpers::NumberHelper(或任何其他帮助类/模块)。

    class QuotePdf < Prawn::Document
      include ActionView::Helpers::NumberHelper # <-
    
      def initialize(quote)
        super()
    
        text "sum: #{number_with_precision(quote.sum)}"
      end
    end
    

    【讨论】:

    • 在 Rails 3.2.11 中为我工作得很好。西克弗里德没有。谢谢!
    • include 必须在最新的 Rails 版本的类之外(在定义类之前)!!
    【解决方案2】:

    只需将 view_context 传递给 Prawn 子类初始化程序。

    def initialize(quote, view_context)
      super()
      @view = view_context
    end
    

    在Controller中,改为:

    QuotePdf.new(@quote, view_context)
    

    然后在 Prawn 子类中,这将起作用:

    @view.number_with_precision(quote.sum)
    

    【讨论】:

    • 我更喜欢这种方法,因为它使@view 及其方法与众不同。这样一来,您就不会从 ActionView 中意外获得 Prawn::Document 中的某些内容。
    【解决方案3】:

    如果 iafonov 解决方案不起作用,您可能只需要包含 NumberHelper 而不带前缀。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-07
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      相关资源
      最近更新 更多