• 12 augustus 2014
  • Leestijd: 1 minuut

Sharing Rails Assets using Git Submodules

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 (opent in nieuw tabblad) (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 (opent in nieuw tabblad) 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:

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.

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.

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).

Gedeelde modules

Sourcetree (opent in nieuw tabblad) with the shared assets submodule

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

git submodule update --init

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.