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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With