views:

112

answers:

3

I'm trying to understand what does and doesn't work in Ruby gems (primarily from the perspective of creating one for myself to reuse functionality from one project to the next).

When you create a Ruby gem, are you limited to including only Ruby functionality or could you create a gem that consisted of Rails templates, CSS files and JavaScripts?

If so, how would the user of the gem access those resources in a Rails project (besides adding a 'config gem' statement to the environment.rb file?

+1  A: 

No it doesn't. Gems are code libraries, not static files.

When you load a gem, you don't move the files to your public directory. You load a ruby file and get access to a module. So, you can only execute ruby code within it.
But, your ruby code can give you some helpers allowing you to easily build your design for example.

If you want to include some static file resources in each of your ruby projects, I'd see two solutions:

  • Create a template project, including all the css, javascript etc. that you use every time. You can take suspenders as an example of this.

  • Create a new repository with all these static files and add it as a submodule (with git or svn) and include it in each of your projects.

The first solution would be my favorite, but you might want to take the other one.

Damien MATHIEU
+1  A: 

As dmathieu notes, gems are for ruby libraries that are installed in the system load path, not for things that go into your project directory. If you do want to package your rails project skeleton as a gem, though, it would be simple enough to have a small ruby executable that served as a generator to copy the skeleton project tree into a target directory. You could then package the whole thing up into a gem, your skeleton files could sit in the gem directory, and you could say generate_new_project someproject to copy them into your new project directory.

Martin DeMello
A: 

You can easily add partials and other HAML, Builder, or ERB views. The following structure should work:

# in my_gem/rails/init.rb
ActionController::Base.append_view_path(File.expand_path(File.join(File.dirname(__FILE__), '..', 'views')))

# in my_gem/views/my_gem/_some_partial.html.erb
This is a partial from MyGem!

# in your_rails_app/views/some_controller/some_view.html.erb:
<%= render :partial => '/my_gem/some_partial' -%>

That doesn't directly answer your question about static files, though. Often the best bet is a generator that copies the CSS, JS, and other files to your public directory. Alternatively, you could use a StaticFilesController and put the static files in that views directory.

James A. Rosen