home

Sharing Rails Assets using Git Submodules

written by on · Comments

Recently we needed two independent Ruby on Rails apps to share some parts of their assets. Both applications are using the same CSS and Javascript files for the main layout. We wanted to maintain those files in one place, without copying files over and over again.

Using a Rails engine (that contains the CSS and Javascript files) seems to be the most obvious way to achieve this. But, we found this not to be the most practical solution during development:

  1. A Rails engine is a separate project in your text-editor, switching between these projects can be annoying.

  2. You need a lot of discipline to commit changes on the Rails engine, as you are not being forced to do this in your normal commit flow.

  3. For just sharing some assets, a Rails engine seems like overkill.

We looked further and figured out that Git submodules solve many of these issues. Basically, you just create a git repository with the javascripts and stylesheets folders and put your shared files in place, like this:

1
2
3
shared-assets/javascripts/menu-interactions.js.coffee
shared-assets/stylesheets/layout.scss.css
shared-assets/stylesheets/menu.scss.css

The next step is to add your shared assets repository as a git submodule to both of your Rails projects.

1
git submodule add git@github.com:yourname-here/shared-assets.git app/assets/shared

Rails needs to know that it has to look for the shared assets folder. You can do this by extending the assets paths in the application.rb file.

1
2
config.assets.paths << "#{Rails.root}/app/assets/shared/stylesheets"
config.assets.paths << "#{Rails.root}/app/assets/shared/javascripts"

Working with the shared assets

Your shared assets are now in the app/assets/shared directory in your Rails application. Changes within the submodule are tracked by your favorite Git client (although we had some issues with Github’s Mac client).

Sourcetree initializes submodules automatically and pulls the submodule while you pull your project. You can do it yourself manually with the following Git commands:

1
git submodule update --init
1
git submodule foreach git pull origin master

Conclusion

Git submodules prove to be handy while developing Moneybird. Style changes for multiple applications are now applied within minutes, while keeping a comfortable workflow.

comments powered by Disqus