如何在 gemfile 中不存在的 rake 任务中要求 gem?

问题描述 投票:0回答:1

我正在尝试在 rake 任务中使用 gem,但我不想将其包含在开发版本中。所以不在 Gemfile 的开发部分。

我不想将它包含在 Gemfile 中,因为它安装起来很慢,而且在 M2 Mac 上它并不总是有效。

所以我试图只将它包含在将要使用它的 rake 任务中。

这是我设计的例子

namespace :utility do
  task contrived_test_funct: :environment do
    begin
      gem 'rmagick'
    rescue LoadError
      system("gem install rmagick")
      gem 'rmagick'
    end

    require 'RMagick'
    file_names = Dir.glob(File.join("/tmp", "**", "*"))
    file_names = file_names.select { |f| f.include?(".pdf") }
    file_names.each do |file_name|
      im = Magick::Image.read(file_name)
      im[0].write(filename.gsub(".pdf",".jpg"))
    end
  end
end

这应该只是将所有 PDF 放在我的临时目录中,然后将它们作为 jpg 输出。如果我的 gemfile 中有 gem 并删除开始/救援块,它在我的本地系统上一切正常。

当我删除 gemfile 更改并取消注释 begin/rescue 块时,它倒塌了

我明白了

Gem::LoadError: rmagick is not part of the bundle. Add it to your Gemfile.

问题:我如何才能只在 Rails 应用程序/回购中的特定 rake 任务中需要 gem?

ruby-on-rails rake-task
1个回答
1
投票

我有一个部分解决方案。不完美,但它让我跨越了界限。

您可以在 rails gemfile 中添加一个新的 gem 组

group :special_group, optional: true do
  gem 'rmagick'
end

然后在rake任务中你可以要求宝石。您还可以捕获错误并让您的开发人员知道如何安装 gem。

begin
  require 'RMagick'
rescue LoadError
   abort("RMagick is selectively installed, Run `bundle config set --local with rmagick`" +
 "and then bundle install and this rake task again")
end
© www.soinside.com 2019 - 2024. All rights reserved.