1

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)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

def self.headers doesn't work either. So you recommend I make CsvVerify a class instead and make EmployeeCsvImporter inherit it? Also I am not new to ruby, but am to writing modules. Never found similar concept in other languages and have to master it some day.
you'd need to extend your class with the module that provides the header method. I suggest you first write out the full functionality of your class and then decide how and if you want/need to split it up in modules. .
ok extend works, thanks, but that means @config will be a class variable?
yes. You are configuring the headers from class level in EmployeeCsvImporter. As said: I'd first write the whole functionality inside a single class to have something working. Then make it re-usable by extracting. Especially if you are new to this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.