Skip to content

Generators

Yuji Hanamura edited this page Aug 20, 2018 · 4 revisions

A great use for Thor is creating custom generators. Combining Thor::Group, Thor::Actions and ERB templates makes this very easy. Here is an example:

class Newgem < 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
    template('templates/newgem.tt', "#{name}/lib/#{name}.rb")
  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

Doing a thor -T will show how to run our generator. It should read: thor newgem NAME. This shows that we have to supply a NAME argument for our generator to run.

The create_lib_file uses an ERB template. This is what it looks like:

class <%= name.capitalize %>
end

The arguments that you set in your generator will automatically be passed in when template gets called. Be sure to read the documentation for more options.

Running the generator with thor newgem devise will create two files: "devise/lib/devise.rb", and "devise/test/devise_test.rb". The user will then be asked (via a prompt by the yes? method) whether or not they would like to copy the MIT License. If you want to change the test framework, you can add the option: thor newgem devise --test-framework=rspec.

This will generate two files: "devise/lib/devise.rb" and "devise/spec/devise_spec.rb".

Clone this wiki locally