简体   繁体   中英

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 .

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.

What is a clean way to explicitly load these bundled rake tasks in my application, so that I can give the argument?

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. The tasks are added in lib/sprockets/railtie.rb in that gem, where L60-61 (in v2.0.1) is:

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

and if we look at lib/sprockets/rails/task we see:

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. As you can see, no arguments are passed to super , so the SprocketsTask will be initialized with the default argument. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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