Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run custom code before any asset precompile in Rails?

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.

like image 798
btown Avatar asked Jan 04 '15 02:01

btown


People also ask

How do you Precompile assets Rails in production?

To compile your assets locally, run the assets:precompile task locally on your app. Make sure to use the production environment so that the production version of your assets are generated. A public/assets directory will be created. Inside this directory you'll find a manifest.

What does rake assets Clean do?

The clean it removes the old versions of the precompiled assets while leaving the new assets in place. Show activity on this post. rake assets:clean removes compiled assets. It is run by cap deploy:assets:clean to remove compiled assets, generally from a remote server.

What is rake Precompile?

rake assets:precompile. We use rake assets:precompile to precompile our assets before pushing code to production. This command precompiles assets and places them under the public/assets directory in our Rails application.


1 Answers

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
like image 181
Michael Radionov Avatar answered Oct 12 '22 11:10

Michael Radionov