brad
brad

Reputation: 9773

How do I keep my current model in scope inside my method

I have a Rails model and in one of the methods I am generating a pdf using prawn like so;

class Report < ActiveRecord::Base

  def pdf_output
    Prawn::Document.new do
      text "Start date: #{start_date.strftime('%e %b %Y').squish}"
    end
  end

end

In that text method I am trying to output the start_date attribute of my report model. Instead I get the following error

NoMethodError in ReportsController#show

undefined method `start_date' for #<Prawn::Document:0x007fdafbce6930>

So my start_date method is referring to my Document object instead of my Report object. How do I access the variables and methods of my report object from inside this block?

Upvotes: 4

Views: 171

Answers (1)

mu is too short
mu is too short

Reputation: 434955

The usual JavaScript trick should work:

def pdf_output
  report = self
  Prawn::Document.new do
    text "Start date: #{report.start_date.strftime('%e %b %Y').squish}"
  end
end

Just grab a reference to the self you need so that you don't have to worry about what Prawn is doing to self inside your block.

Upvotes: 5

Related Questions