19

Something like (in an initializer):

Sprockets.before_precompile do
  # some custom stuff that preps or autogenerates some asset files
  # that should then be considered in the asset pipeline as if they were checked in
end

Specifically, I'd like to run a gulp task to bundle some Javascript with some special preprocessors, and I'd rather not rewrite my gulpfile to get the asset pipeline to handle everything... and I also want this to work on Heroku without needing a custom buildpack if at all possible. Any thoughts? Presumably Sprockets has these types of hooks.

btown
  • 2,273
  • 3
  • 27
  • 38

1 Answers1

34

As I can see from the source, Sprockets does not have such a hook, but you could use rake task hooks. For example, you would create a rake task that starts all the preprocessors, gulp, etc, so this task could be put before precompilation.

# lib/tasks/before_assets_precompile.rake

task :before_assets_precompile do
  # run a command which starts your packaging
  system('gulp production')
end

# every time you execute 'rake assets:precompile'
# run 'before_assets_precompile' first    
Rake::Task['assets:precompile'].enhance ['before_assets_precompile']

Then you just run rake assets:precompile, and as a result the task before_assets_precompile will be executed right before it.

Also make sure to use system instead of exec, because exec will exit the process on a stage of running this pre-task and will not run assets:precompile after itself as it was expected.

Sources:

  1. Rake before task hook
  2. http://www.dan-manges.com/blog/modifying-rake-tasks
Community
  • 1
  • 1
Michael Radionov
  • 12,859
  • 1
  • 55
  • 72
  • Would this work with the automatic asset-compilation that happens in `development` mode? – Suan Jan 06 '16 at 15:09
  • @Suan, if I am not mistaken, live compilation for development env is done on the page load, running a gulp task to build an app every time page is reloaded seems a bit overkill to me. I guess for this case it's better to use gulp watch, so it will build the app only when you make changes to source files, and on page reload you'll get the most recent assets prepared by gulp. I am not sure if there is a similar Rake task for live compilation though. – Michael Radionov Jan 06 '16 at 18:20