16
votes

I want to write a gem that, once bundled to a Rails 3.1 Gemfile, includes some boilerplate CSS and JS files.

I know about generators, but how could I do this without them so that the gem's effects can be added and removed without anything more than editing one line in the Rails Gemfile?

Ideally, I'd like the gem to include its default CSS/JS upon installation, then let the user use the generator to generate the CSS/JS files if they want to make any modifications.


Here's a sample gem that I copied from jquery-rails, which includes javascript files without generators.

css_gem/
  lib/
    css_gem.rb       {1}
    css_gem/
      engine.rb      {2}
  app/
    assets/
      stylesheets/
        css_gem/
          index.css  {3}
          base.css   {4}

{1} lib/css_gem.rb

module CssGem
  require "css_gem/engine"
end

{2} lib/css_gem/engine.rb

module CSSGem
  class Engine < Rails::Engine
  end
end

{3} app/assets/stylesheets/css_gem/index.css

/*
 *= require base
 */

{4} app/assets/stylesheets/css_gem/base.css

.custom { color: red; }

Rails Gemfile

gem 'css_gem', :path => 'path_to_my_local_gem'

This isn't working for me and Rails doesn't see the CSS file. What am I doing wrong?


Solution: Thankfully, I found a video to hold my hand: http://house9.blogspot.com/2011/06/rails-31-asset-gem.html

I had to still manually add *= require css_gem to my Rails stylesheet manifest (app/assets/stylesheets/application.css). Duh.

4

4 Answers

7
votes

There is a great article by Zurb on how they packaged foundation assets as gem:

"Yetify Your Rails: New Foundation Gem and How To Gemify Your Own Assets"

2
votes

DISCLAIMER - I have not tried this yet. You can leverage the Asset Pipeline in Rails 3.1 to make assets in your gem available to client apps without the use of generators.

Have not found a practical example of this in use yet but here is the link to the early docs

http://edgeguides.rubyonrails.org/asset_pipeline.html http://edgeguides.rubyonrails.org/asset_pipeline.html#adding-assets-to-your-gems

1
votes

For those who looking for straight answer

If you have these assets in your gem :

app  
|__ assets  
   |__ javascripts
   |  |__ foo
   |     |__ foo.js
   |
   |__ stylesheets
      |__ foo
         |__ foo.css

The assets will be included automatically if you create a generator(in your gem) like this :

# lib/generators/foo/install/install_generator.rb

module Foo
  module Generators
    class InstallGenerator < Rails::Generators::Base

      def add_javascripts
        append_file 'app/assets/javascripts/application.js', "//= require foo/foo\n"
      end

      def add_stylesheets
        inject_into_file 'app/assets/stylesheets/application.css', " *= require foo/foo\n", :before => /\*\//, :verbose => true
      end
    end
  end
end