rails rake task with globally installed gem

203 views Asked by At

I'm trying to write a rake file to import data from csv, and I want to use smarter_csv gem. I have the gem installed globally (I don't want to add it to my Gemfile because it's a one-off task).

In my rake file I require 'smarter_csv' but when I run the task I get the following error:

rake aborted!
LoadError: cannot load such file -- smarter_csv

Every rake example I can find tells you to just require 'foo'. I can run the code manually in irb after requiring smarter_csv.

What am I missing?

(If it matters, I'm using rbenv on macOS Catalina)

2

There are 2 answers

1
benjessop On BEST ANSWER

If you do want to load a gem without having it in your Gemfile you can do the following in your rake task:

$: << '/Users/<user>/.rvm/rubies/ruby- 
x.x.x/lib/ruby/gems/x.x.x/gems/smarter_csv-x.x.x/lib'
require 'smarter_csv'

I think the option to have the gem in your Gemfile with the require: false option is more suitable however. The gem won't be loaded until you specifically require it.

0
Kumar On

Rails uses bundler, and loads the gems mentioned in gemfile into memory. Doesn't look like you've any other option.

I had a similar use case, I tried putting it into a development group like so,

group :development do
  gem 'smarter_csv'
end