Friday, February 3, 2012

Ship generators with your Ruby gems

Say I'm building a gem and I want it to do three things.  

  1. create a new route in the gem user's routes.rb file 
  2. add some code that will be executed every time they start their app, and  
  3. place a controller in their rails controller directory.

How would I allow the gem user to do this with one command?

Let's build a quick gem for a rails 3.0+ app. This post assumes that you understand the basics of creating a Ruby gem.

In the terminal run:



Here, when Rails sees the 'generators' directory, the generator we are going to create becomes available to the 'rails generate' command. The 'templates' directory will store all the files and text the user may want to add to their app. Now open install_generator.rb and add the following:



For the three methods above to work, you need to specify 'thor' as a dependency in your my_gem.gemspec file. There, you will also need to specify your 'lib' directory as an executable (for an example of a gemspec file go here).


These three methods will be executed when your user runs the generator.
I use the 'template' method instead of the better-sounding 'copy_file' method so that we can place all of our files into a 'templates' directory. The 'template' function adds this directory to the generator's path. The ‘template’ method also executes any ERB tags found in your template files, and, while this can be powerful, we need to escape them if we're placing 'html.erb' files into the user's 'view' directory lest Rails throws a nomethod error when trying to execute them - we do this by using a double percent (%%) like so:

So far, in the templates directory, we've made the files we want to copy into our gem user's rails app.  In the install directory, we've made the actual generator itself.  And in the root of our gem, we've ensured that our gemspec file lists 'thor' as a dependency and the 'lib' directory as an executable.

We're ready to create the gem.


No comments:

Post a Comment