Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I really need to require csv gem with Rails?

My question is simple:

Do I have to require 'csv' on a class using Ruby on Rails?

If i open a rails console and tryied to use CSV gem it works, but do I have to do that in the file?

like image 300
Max Forasteiro Avatar asked May 28 '18 18:05

Max Forasteiro


1 Answers

The CSV library is part of the ruby standard library; it is not a gem (i.e. a third party library).

As with all of the standard library (unlike the core library), csv is not automatically loaded by the ruby interpreter. So yes, somewhere in your application you do need to require it:

irb(main):001:0> CSV
NameError: uninitialized constant CSV
        from (irb):1
        from /Users/tomlord/.rbenv/versions/2.4.4/bin/irb:11:in `<main>'
irb(main):002:0> require 'csv'
=> true
irb(main):003:0> CSV
=> CSV

In a large project such as a rails application, you may find that csv has actually been already loaded; perhaps somewhere "obscure" like within a gem, or somewhere in config/initializers/*, or config/application.rb.

However, it's generally a bad idea to rely on libraries being loaded in "unrelated" places like this; doing so could lead to to inadvertently breaking other code when you change it, or gradually loading more and more libraries here, even when some are no longer needed.

So to cut a long story short: Yes, I would recommend writing require 'csv' at the top of any file which uses the CSV library. Or, within a larger project which will clearly need this library loaded and used in many places, you could consider just loading it globally in places like config/application.rb

like image 118
Tom Lord Avatar answered Sep 28 '22 04:09

Tom Lord