In the following code, why does the data variable work properly as a class variable but not an instance variable? (Note: I tried to simplify/reproduce only the necessary bits of the script to have the question make sense. If more is needed I can post the full script.)
require 'prawn'
class Test
include Prawn
def initialize (data, filename) #data is an array of arrays
@@data = data #this is the variable in question, when @data the script fails
@filename = filename
end
def to_pdf
Document.generate("#{@filename}.pdf") do #included from Prawn
@@data.each do |item|
do some stuff to the data
end
make_table with the data that's been worked on
end
end
end
test_run = Test.new([[1, 2, 1], [1, 2, 2]], "testfile.pdf")
test.to_pdf
If @@data is instead @data the script returns undefined method 'each' for nil:NilClass (NoMethodError) Why is that? Shouldn’t an instance variable be equally accessible to the included module? (also why is it ok that the @filename variable is an instance method?)
From the fine manual:
Your block in
to_pdfis being evaluated in the content of aPrawn::Documentinstance, not within the context of your object and that means that there is no@datainstance variable so@datais created with a value ofnilwhen you try to access it. You probably want to use a block with a single argument: