Search code examples
ruby-on-railsrubyrakesmartercsv

rails rake task with globally installed gem


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)


Solution

  • 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.