简体   繁体   English

使用全局安装的 gem 的 rails rake 任务

[英]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.我正在尝试编写一个 rake 文件来从 csv 导入数据,并且我想使用 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).我在全局安装了 gem(我不想将它添加到我的 Gemfile 中,因为它是一次性任务)。

In my rake file I require 'smarter_csv' but when I run the task I get the following error:在我的 rake 文件中,我需要“smarter_csv”,但是当我运行任务时,出现以下错误:

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

Every rake example I can find tells you to just require 'foo'.我能找到的每个 rake 例子都告诉你只需要 'foo'。 I can run the code manually in irb after requiring smarter_csv.需要 smarter_csv 后,我可以在 irb 中手动运行代码。

What am I missing?我错过了什么?

(If it matters, I'm using rbenv on macOS Catalina) (如果重要的话,我在 macOS Catalina 上使用 rbenv)

Rails uses bundler, and loads the gems mentioned in gemfile into memory. Rails 使用 bundler,并将 gemfile 中提到的 gem 加载到内存中。 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

If you do want to load a gem without having it in your Gemfile you can do the following in your rake task:如果你确实想加载一个 gem 而不将它放在你的 Gemfile 中,你可以在你的 rake 任务中执行以下操作:

$: << '/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.我认为使用require: false选项在 Gemfile 中包含 gem 的选项更合适。 The gem won't be loaded until you specifically require it.除非您特别需要,否则不会加载 gem。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM