Marko Avlijaš
Marko Avlijaš

Reputation: 1659

How to avoid using instance variables in modules?

I am sketching out how would CsvVerify module work. Is there a way to not polute class that will include the module with instance variables

Idea is inspired by virtus and goes something like this:

employee_csv_importer.rb (using the module)

class EmployeeCsvImporter
  include CsvVerify

  headers 'ID', 'First Name', 'Last Name', 'Title or Department',
    'Age', 'Native Language', 'Fluent in English?'
end

csv_verify.rb

module CsvVerify
  puts "included"

  def headers(*names)
    @config = Config.new
  end
end

config.rb

module CsvVerify
  class Config

  end
end

So how do I reorganize this to avoid polluting EmployeeCsvImporter with @config?

PS. And why doesn't this even work now?
Why do I get this output from running employee_csv_importer.rb?

included
/data/gems/csv_verify/examples/1_employees.rb:6:in `<class:EmployeeCsvImporter>':
undefined method `headers' for EmployeeCsvImporter:Class (NoMethodError)

Upvotes: 1

Views: 83

Answers (1)

Pascal
Pascal

Reputation: 8646

I'd suggest you start writing your functionality without module and include first. This helps shape out the structure, especially if you are new to Ruby.

The methods added by including CsvVerify are added as instance methods, not class methods. Therefore you have this NoMethodError.

Upvotes: 1

Related Questions