pcreux / csv-importer

CSV Import for humans on Ruby / Ruby on Rails
MIT License
590 stars 67 forks source link

Cannot access instance variable in after_build #104

Closed unikitty37 closed 3 years ago

unikitty37 commented 3 years ago

I'm trying to pass in a User object which needs to be set in after_build, but setting a class variable in the initializer sets it on the CSVImporter class, and after_build seems to run in the context of CSVImporter::Row, meaning all attempts to access the instance variable return nil.

Is there a way to access the instance variable in after_build?

class MyImporter
  include ::CSVImporter

  model Ticket

  …

  after_build do |ticket|
    ticket.created_by = @user
  end

  def initialize(user)
    @user = user
  end
end
pcreux commented 3 years ago

Following the README, this should work:

class MyImporter
  include ::CSVImporter

  model Ticket
end

user = User.first!

MyImporter.new(...) do
  after_build do |ticket|
    ticket.created_by = user
  end
end