получение «неопределенной локальной переменной или ошибки метода» для создания pdf-файла креветок только на сервере heroku, а не локально - PullRequest
0 голосов
/ 01 мая 2019

Всякий раз, когда я вношу новую запись в базу данных, она не распознается креветкой, пока я не перезапущу свой сервер Heroku. У меня нет проблем локально (с помощью Cloud9), однако, при использовании heroku я получаю сообщение об ошибке вроде:

NameError (неопределенная локальная переменная или метод `method_199 '"

, где method_199 не найдено, потому что я только что добавил его в базу данных. Если я повторно разверну свой код на heroku, он распознает method_199.

Кажется, это проблема только с моей pdf-креветкой. На сайте heroku остальная часть базы данных, кажется, обновляется и отвечает просто отлично (имеется в виду, что я могу сделать обновление, и оно появляется без необходимости повторного развертывания приложения)

pdf.rb

class ReportTwoPdf < Prawn::Document
 def initialize(property, current_user, start_date, end_date)
 super(top_margin: 50)

@property = property
@current_user = current_user
@start_date = start_date
@end_date = end_date

# @activity_types.each do |type|
# eval("test_#{type.id}")
# end


current_user.activity_types.each do |type|
  if @property.activities.where(activity_type_id: type.id).where(:date => 
  (@start_date..@end_date)).count > 0
    eval("method_#{type.id}")
  else
  end
end

end

ActivityType.all.each do |type|
define_method("method_#{type.id}") do
  move_down 20
  a = [1,
       type.subject_toggle == "Show" ? 1 : nil,
       type.contact_toggle == "Show" ? 1 : nil,
       type.agent_toggle == "Show" ? 1 : nil,
       type.customer_toggle == "Show" ? 1 : nil,
       type.detail_toggle == "Show" ? 1 : nil,
       type.outcome_toggle == "Show" ? 1 : nil,
       type.cost_toggle == "Show" ? 1 : nil,
       type.duration_toggle == "Show" ? 1 : nil].compact.length - 1

  font "Nunito"
  text type.title, :align => :left, size: 12, style: :bold
  move_down 5
  table eval("row_#{type.id}"), :position => :center, :width => 540, 
:column_widths => {0 => 50,1 => @min_width, a => 60},
                        :cell_style => {:font => "Nunito", :size => 9} do
    row(0).font_style = :bold
    columns(0..8).align = :center
    self.row_colors = ["F0F0F0", "FFFFFF"]
    self.header = true
  end
end
end

Контроллер:

 def create_pdf
@property = Property.find(params.fetch("id_to_display"))
@current_user = current_user
@start_date = Date.strptime(params.fetch("start_date"), "%Y-%m-%d")
@end_date = Date.strptime(params.fetch("end_date"), "%Y-%m-%d")
@user = current_user

respond_to do |format|
  format.html
  format.pdf do
    pdf = ReportTwoPdf.new(@property, @current_user, @start_date, @end_date)
    send_data pdf.render, :filename => "Report: #{@property.address}.pdf", :type => "application/pdf", disposition: "inline"
  end
end
end

Gemfile

gem "prawn"
gem 'prawn-table'

1 Ответ

0 голосов
/ 01 мая 2019

Такое поведение ожидается, поскольку в производственных классах оцениваются только один раз при запуске сервера. Это, в свою очередь, обычно происходит только при развертывании или масштабировании. Ваши данные в ActivityType, очевидно, могут меняться чаще, чем вы развертываете

Я не понимаю, зачем вам определять эти динамические методы, вы можете обрабатывать ActivityType s, как и любые другие данные:

class ReportTwoPdf < Prawn::Document
  def initialize(property, current_user, start_date, end_date)
    super(top_margin: 50)

    @property = property
    @current_user = current_user
    @start_date = start_date
    @end_date = end_date


    current_user.activity_types.each do |type|
      if @property.activities.where(activity_type_id: type.id).where(date: (@start_date..@end_date)).count > 0
        handle_activity_type(type)
      else
      end
    end

  end

  def some_row_similar(type)
    # here goes the code
  end

  def handle_activity_type(type)
    move_down 20
    a = [
      type.subject_toggle,
      type.contact_toggle,
      type.agent_toggle,
      type.customer_toggle,
      type.detail_toggle,
      type.outcome_toggle,
      type.cost_toggle,
      type.duration_toggle
    ].count{|toggle| toggle == "Show" }

    font "Nunito"
    text type.title, align: :left, size: 12, style: :bold
    move_down 5

    table some_row_similar(type), position: :center, width: 540, 
        column_widths: {0 => 50, 1 => @min_width, a => 60},
        cell_style: {font: "Nunito", size: 9} do
      row(0).font_style = :bold
      columns(0..8).align = :center
      self.row_colors = ["F0F0F0", "FFFFFF"]
      self.header = true
    end
  end

end
...