简体   繁体   English

Rails:如何显式初始化与gem捆绑在一起的rake任务?

[英]Rails: How to explicitly initialize rake tasks “bundled” with a gem?

The sprockets gem ships with some rake tasks, which are automatically loaded by rails . sprockets宝石带有一些rake任务,这些任务会由rails自动加载。

The initialise method of that task file can take an argument (namespace of the tasks, defaults to assets ), but because it loaded automatically, there is no way to actually give that argument. 该任务文件的initialise方法可以采用一个参数(任务的命名空间,默认为assets ),但是由于它是自动加载的,因此无法实际给出该参数。

What is a clean way to explicitly load these bundled rake tasks in my application, so that I can give the argument? 有什么干净的方法可以在应用程序中显式加载这些捆绑的rake任务,以便提供参数?

There is no clean way to do this. 没有干净的方法可以做到这一点。 You can see this by looking at the sprockets-rails gem, which initializes sprockets for a rails app. 您可以通过查看sprockets-rails gem来看到此信息,该gem会为rails应用程序初始化链轮。 The tasks are added in lib/sprockets/railtie.rb in that gem, where L60-61 (in v2.0.1) is: 任务添加到该gem的lib/sprockets/railtie.rb中,其中L60-61(在v2.0.1中)为:

require 'sprockets/rails/task'
Sprockets::Rails::Task.new(app)

and if we look at lib/sprockets/rails/task we see: 如果我们查看lib/sprockets/rails/task就会看到:

class Task < Rake::SprocketsTask
  attr_accessor :app

def initialize(app = nil)
  self.app = app
  super()
end

so that's where the initialize method you refer to in your question is called when a rails app is initialized. 因此,在initialize Rails应用程序时,就会在问题中引用您所引用的initialize方法。 As you can see, no arguments are passed to super , so the SprocketsTask will be initialized with the default argument. 如您所见,没有参数传递给super ,因此SprocketsTask将使用默认参数初始化。 And there's clearly no way for you to pass an argument in without monkey-patching. 而且,如果没有猴子打补丁,您显然没有办法传递论点。 If this is something you really need, I'd recommend forking sprockets-rails and either just using your forked version, or perhaps submit a patch so you can get back on the main branch if it's accepted. 如果这是您真正需要的东西,我建议分叉sprockets-rails ,或者只使用您的分叉版本,或者提交补丁程序,以便您可以在接受主分支的情况下返回主分支。

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

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