Posts tagged "generators"

This weekend during Rails Bugmash I stumbled across some nice posts about Rails 3 generators which motivated me to share them and add some comments!

First, David Trasbo wrote a nice guide about how to make your first Rails 3 generator, it covers up all the basic steps including setting it up in a gem. He also puts the deserved attention into Thor::Actions, which contains most helpers you need in a generator, like copy_file, template, create_file, empty_directory and so on.

On another post, Ben Scofield talks about apply method, which is also in Thor::Actions, and how to use it to dry your application templates.

Wait… so Thor::Actions is used both in generators and in Rails application templates? Exactly, Rails’ new generators unifies both application templates and generators API into one. While Thor::Actions holds basic methods, all Rails specific methods like environment, rakefile, generator are in Rails::Generators::Actions. If you already wrote an application template, you will feel more at home when writing a Rails 3 generator.

Paul Barry talks how easy it’s to customize your scaffold to use Rspec, Haml and Factory Girl instead of Test::Unit, Erb and Fixtures. This all works because scaffold is just a meta generator which provides hooks for template engine, test framework, ORM and so forth. A good way to see the hooks system working is by running script/generate scaffold --help before and after Paul changes, so you can see exactly how generators options update depending on the configuration values you set. While I wrote Rspec generators used in the example, he implemented himself Haml and Factory Girl generators and they can all be used as example if you plan to build your own.

Finally, Zigzag Chen wrote about templates customization and how you can change your scaffold controller to use json instead of the xml format. New generators have source paths, so you can customize them simply by copying files to RAILS_ROOT/lib/templates.

Rails Bugmash was excellent to gather feedback and we also got some tickets on Lighthouse, mainly about how generators help can be improved for people starting with Rails. Many thanks to Rails Bridge and besides the posts linked above, there is a generator guide, which may help you get started and maybe write your own post as well. :)

It has been a couple weeks since we first bloged about Devise. At that time, we released version 0.1 and now, after some great feedback, some enhancements and a few bugs fixes, we reached Devise 0.4. So, what changed since then?

I’m lazy, you’re lazy

Devise now comes with generators, so adding up authentication to your app is even easier and quicker to do. First, let’s install Devise if you haven’t yet:

gem sources -a http://gemcutter.org/
gem install devise

And let’s add it to your environment, all together with warden:

config.gem "warden", :version => "0.5.1"
config.gem "devise", :version => "0.4.1"

After setting the gem up, the first generator can be invoked:

script/generate devise_install

And it simply places an initializer at config/initializers/devise.rb. You can check there all devise configuration options, so the initializer fits well as documentation tool too. Some of the new things you can configure since 0.1 release is the :confirm_within period (the time the user can access the site even without confirming his account) and :remember_for period (the time the remember token is valid).

After we configured Devise, we are able create our models. And how hard can that be if we have a generator? So just do:

script/generate devise User

It’s going to create a model User, add map.devise_for :users in routes.rb and a migration file. And before we proceed, we just need to configure default_url_options for ActionMailer in config/environments/development.rb (the config below is for development, be sure to properly set them for test and production too):

config.action_mailer.default_url_options = { :host => 'localhost:3000' }

And have at least a route named root in our config/routes.rb (by default, devise will look for user_root_path, if none is defined, is uses root_path):

map.root :controller => "your_controller"

Now we just need to run migrations and we will be able to create our first user in the console:

User.create!(:email => "your@email.com", :password => "secret")

Now just start your web server and you will be able to sign your user in at /users/sign_in, request for another confirmation code to be sent, request a code to reset your password and so forth.

Just remember that Devise does not say anything about the sign up process, that’s why you have to create your users in console.

Customization

We also know that you want to customize your views, to use something like Formtastic instead of the default markup. Well, guess who is here to help you?

Generators! The command below will make a copy of all devise views to your application, including locale files, for flash messages configuration:

script/generate devise_views

Laziness for all!

We know that you are lazy and not just with ActiveRecord. You want to be lazy with Datamapper, Mongomapper, Couchrest… This is why we worked on making Devise a little bit more agnostic, all your ORM has to do is have an API similar to ActiveRecord (finder and callbacks mainly).

Besides, if you already travelled a bit on Warden world, you will see that there is a lot more than Devise, including some strategies for OAuth. So we are also working on making Devise compatible with such new strategies as well, that’s why you can already see a config.warden hook on the initializer.

Deprecations

Since things are getting really easy, we need to ask something back from you. Just watch out for to deprecations in Devise 0.4.0:

1) :authenticable is a typo, so we fixed that renaming it to :authenticatable. If you used Devise 0.3.x, you could see some deprecation warnings. However, in Devise 0.4.0 such warnings were removed. Tip: be sure to check your migration!

2) We had a notifier inside Devise called Notifier. We decided to follow Clearance convention and rename it to DeviseMailer. You will need to change your views from notifier to devise_mailer and your locale yml from notifier to mailer.

We hope you enjoy Devise as much as we do! And, as previously, we also have an example app in Github to help you get started too.

This summer I was selected with Josh Peek, Emilio Tagua and Nelson Crespo to work with Rails on Google Summer of Code (GSoC), which Nelson named as the Rails Summer Quartet. :)

Here, at Plataforma, we use a set of tools on our projects, which includes Inherited Resources, Remarkable and Formtastic. 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.

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.

1. So, what about Thor?!

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

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

And then can be invoked as:

> thor speak:hello jose
Hello jose
 
> thor speak:hello jose –-loudly
Hello JOSE

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:

  • It has a powerful options parser;
  • Thor classes can be inherited and all tasks from the class are copied to the child;
  • Thor classes are self contained. The example above can be invoked straight from your ruby code as Speak.new.hello(“jose”).

Then I was able to create a ROADMAP to Thor:

  • Add actions like copy_file, template, empty_directory to Thor;
  • Move all user input and output logic to its own class, so anyone can customize it;
  • Extend even more Thor options parser to add support to hashes (as in Rails name:string age:integer on generators) and arrays;
  • Add an invocation mechanism, so I can invoke one task from another Thor task.

2. An example

Let’s see an example on how you can create your own generators with Thor. For example, a generators that stubs out a new gem structure:

class NewgemGenerator < Thor::Group
  include Thor::Actions
 
  # Define arguments and options
  argument :name
  class_option :test_framework, :default => :test_unit
 
  def self.source_root
    File.dirname(__FILE__)
  end
 
  def create_lib_file
    create_file "#{name}/lib/#{name}.rb" do
      "class #{name.camelize}\nend"
    end
  end
 
  def create_test_file
    test = options[:test_framework] == "rspec" ? :spec : :test
    create_file "#{name}/#{test}/#{name}_#{test}.rb"
  end
 
  def copy_licence
    if yes? "Use MIT license?"
      # Make a copy of the MITLICENSE file at the source root
      copy_file "MITLICENSE", "#{name}/MITLICENSE"
    else
      say "Shame on you…", :red
    end
  end
end

You can see from the example above that we are inheriting from Thor::Group and not Thor. In Thor, each method corresponds to a task, which can be invoked on its own. In Thor::Group, you invoke all tasks at once, in the order they are declared. This is interesting because you split your script/generator into several methods. It improves readability and allows anyone to inherit from your generator and change just one step in the process.

The next step, on lines 4 and 5, is to define arguments and options for the class. Arguments are required to be given right after the executable while options are given with switches. The newgem above can be invoked as:

newgem remarkable

And it will create two files: “remarkable/lib/remarkable.rb”, “remarkable/test/remarkable_test.rb” and prompt the user (with the use of the method yes?) if we wants to copy the MITLICENSE. If you want to change the test framework, you can give it as an option:

newgem remarkable --test-framework=rspec

Now it generates “remarkable/lib/remarkable.rb” and “remarkable/spec/remarkable_spec.rb”.

The generation methods are kept into the Thor::Actions module, which is included on top of our class. It holds all the scripting methods, which are: copy_file, create_file, directory, empty_directory, get, inject_into_file and template. All those actions can be revoked, so Thor knows how to do and undo the process (like in script/generate and script/destroy).

Even more, some of Rails templates methods was moved to Thor, like: inside, run, run_ruby_script, gsub_file, append_file and prepend_file. So whenever creating scripts with Thor, those methods will be available to make your life easier.

Finally, all user iteration methods are handled by Thor::Shell classes by say, ask, yes? and no? methods. Thor ships with two Shell implementations: Basic and Color. If you mantain an IDE for Rails, you can build your own shell and make the user interaction through it.

3. What is more?

Thor is used as base in Rails::Generators, where Rails extend it to provide Rails specific functionalities, as hooks for ORM, Test framework and so on. This will be my talk subject on Rails Summit Latin America, 13th October, in São Paulo, Brazil.

If you can join us or not, be sure to grab our RSS feed and keep on checking, we will discuss about it here too.