Rails 4.0 - Creating a Gem with Image Assets

August 14, 2013


Creating your own gem is simple thanks to Bundler.  This RailsCast gives a great explanation of the process.  But I ran into a few problems yesterday while trying to create a new gem that is essentially a wrapper for a lightweight Javascript wysiwyg editor called jHtmlArea.  This editor, like many other useful Javascript plugins, includes images as well as scripts and css. 

The issue was that when I precompiled the assets for my Rails 4.0 application prior to deployment, the images specified in this gem were not getting included in the manifest or copied to public/assets/.  The other assets included in the gem (stylesheets and javascripts) were getting handled properly.

I thought I was following standard conventions, with a directory structure in my gem like this:

vendor
|-- assets
     |-- images
     |-- javascripts
     |-- stylesheets

and with an engine.rb file like this:
module Jhtmlarea
  if defined?(::Rails) and Gem::Requirement.new('>= 3.1').satisfied_by?(Gem::Version.new ::Rails.version)
    module Rails
      class Engine < ::Rails::Engine
    end
  end
end
as explained somewhat in this Rails Guide
In comparing my gem to the actively supported Bootstrap-Sass gem, I noticed that its authors had added an initializer to engine.rb, so I did something similar:
module Jhtmlarea
  if defined?(::Rails) and Gem::Requirement.new('>= 3.1').satisfied_by?(Gem::Version.new ::Rails.version)
    module Rails
      class Engine < ::Rails::Engine
        initializer "jhtmlarea.assets.precompile" do |app|
          app.config.assets.precompile +=
            %w(jHtmlArea.png 
jHtmlArea_Toolbar_Group_BG.png
jHtmlArea_Toolbar_Group__Btn_Select_BG.png) end end end end end
That fixed my problem :)   But interestingly, in the course of debugging this issue, I had installed another well-supported and useful gem: jquery-datatables-rails and found that it also suffered from the same issue -- so it seems to me that something may have changed recently, possibly in Rails 4.0 or Sprockets 2.10 or Sprockets-Rails 2.0 that makes the addition of this initializer necessary.

Update 8/26/2013

See the succinct comment by bambycha for a simple workaround for 'lazy supported gems'.

Feedback

Your feedback is welcome! If you find any errors in this post or have any additional pointers or insights, please take a moment to register and share your thoughts.



Comments

On August 26, 2013, bambycha wrote:

You don't need pull every lazy supported gem. Simply add config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif) in application.rb. And auto precompile all images.

On August 26, 2013, Dow wrote:

Thanks bambycha! I just tested your solution and you're right. I really appreciate the comment!



You must be logged in to comment

All Posts