Ruby NameError,未初始化常量,使用 Prawn
Ruby NameError, uninitialized constant, using Prawn
对这个错误感到困惑:
NameError in ProductionController#weekly_schedule
uninitialized constant ProductionController::WeeklySchedulePdf
我正在使用 prawn_rails gem,以下代码来自 http://www.sitepoint.com/pdf-generation-rails/。
中的教程
这是我的控制器片段...
class ProductionController < ApplicationController
def weekly_schedule
@tickets = Ticket.where(active: true,
manufacturing_location: session[:factory]).
order(:calendar_date).order(:calendar_order)
if @tickets.size.zero?
@first_day, @last_day = Date.current, Date.current
else
@first_day = @tickets.minimum(:calendar_date)
@last_day = @tickets.maximum(:calendar_date)
#@dayspan = (@last_day - @first_day).to_i
end
vars = [@tickets, @first_day, @last_day]
respond_to do |format|
format.html
format.pdf do
pdf = WeeklySchedulePdf.new(vars)
send_data pdf.render, filename: 'weekly_schedule.pdf', type: 'application/pdf'
end
end
end
还有我的 Prawn 文件,在 app/pdf/weekly_schedule.rb
class WeeklySchedulePdf < Prawn::Document
def initialize(vars)
super
@tickets = vars.first
@first_day = vars.second
@last_day = vars.third
#header
#text_content
#table_content
end
app/pdf
中的源文件不会被 Rails 自动发现(它们曾经是)。您需要将路径添加到 config.autoload_paths
中以使 class 可用。
# config/application.rb
config.autoload_paths += %W(#{config.root}/app/pdf)
http://guides.rubyonrails.org/configuring.html#configuring-rails-components
原来我所要做的(使用 rails 4.2)是将文件从 weekly_schedule.rb
重命名为 weekly_schedule_pdf.rb
对这个错误感到困惑:
NameError in ProductionController#weekly_schedule
uninitialized constant ProductionController::WeeklySchedulePdf
我正在使用 prawn_rails gem,以下代码来自 http://www.sitepoint.com/pdf-generation-rails/。
中的教程这是我的控制器片段...
class ProductionController < ApplicationController
def weekly_schedule
@tickets = Ticket.where(active: true,
manufacturing_location: session[:factory]).
order(:calendar_date).order(:calendar_order)
if @tickets.size.zero?
@first_day, @last_day = Date.current, Date.current
else
@first_day = @tickets.minimum(:calendar_date)
@last_day = @tickets.maximum(:calendar_date)
#@dayspan = (@last_day - @first_day).to_i
end
vars = [@tickets, @first_day, @last_day]
respond_to do |format|
format.html
format.pdf do
pdf = WeeklySchedulePdf.new(vars)
send_data pdf.render, filename: 'weekly_schedule.pdf', type: 'application/pdf'
end
end
end
还有我的 Prawn 文件,在 app/pdf/weekly_schedule.rb
class WeeklySchedulePdf < Prawn::Document
def initialize(vars)
super
@tickets = vars.first
@first_day = vars.second
@last_day = vars.third
#header
#text_content
#table_content
end
app/pdf
中的源文件不会被 Rails 自动发现(它们曾经是)。您需要将路径添加到 config.autoload_paths
中以使 class 可用。
# config/application.rb
config.autoload_paths += %W(#{config.root}/app/pdf)
http://guides.rubyonrails.org/configuring.html#configuring-rails-components
原来我所要做的(使用 rails 4.2)是将文件从 weekly_schedule.rb
重命名为 weekly_schedule_pdf.rb