{"id":31,"date":"2009-07-31T16:22:36","date_gmt":"2009-07-31T19:22:36","guid":{"rendered":"http:\/\/blog.plataformatec.com.br\/?p=31"},"modified":"2010-04-22T14:57:45","modified_gmt":"2010-04-22T17:57:45","slug":"creating-your-own-generators-with-thor","status":"publish","type":"post","link":"https:\/\/blog.plataformatec.com.br\/2009\/07\/creating-your-own-generators-with-thor\/","title":{"rendered":"Creating your own generators with Thor"},"content":{"rendered":"

This summer I was selected with Josh Peek<\/a>, Emilio Tagua<\/a> and Nelson Crespo<\/a> to work with Rails on Google Summer of Code (GSoC), which Nelson named as the Rails Summer Quartet<\/a>. \ud83d\ude42<\/p>\n

Here, at Plataforma<\/a>, we use a set of tools on our projects, which includes Inherited Resources<\/a>, Remarkable<\/a> and Formtastic<\/a>. At some point, we were planning on creating generators for each of those tools but still they couldn’t play along. If I wanted a generator that uses all three projects, I needed to create a inherited_remarkable_formtastic generator which is not DRY at all.<\/p>\n

For example, for those who wants to use Datamapper with Rspec, they need to call “ruby script\/generate dm_rspec_model” instead of “ruby script\/generate model”. Since Rails 3.0 is moving towards agnosticism, my GSoC proposal was exactly bring it to rails generators.<\/p>\n

1. So, what about Thor?!<\/h3>\n

One day before the official coding period start, I was staring at this Thor post<\/a> by Yehuda Katz. Thor<\/a> is a rake replacement with support to options parsing:<\/p>\n

class Speak < Thor\r\n  desc \"name\", \"the name to say hello to\"\r\n  method_options :loudly => false\r\n\r\n  def hello(name)\r\n    name.upcase! if options[:loudly]\r\n    puts \"Hello #{name}\"\r\n  end\r\nend<\/pre>\n

And then can be invoked as:<\/p>\n

> thor speak:hello jose\r\nHello jose\r\n\r\n> thor speak:hello jose \u2013-loudly\r\nHello JOSE<\/pre>\n

At that point, I realized that a generator is nothing more than a scripting task (like rake or thor) with some extra methods which makes the creation and copy of files easy. Thor had several features which convinced me that it was the best solution to build generators on top of:<\/p>\n