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

  def create_lib_file
    template('templates/', "#{name}/lib/#{name}.rb")

  def create_test_file
    test = options[:test_framework] == "rspec" ? :spec : :test
    create_file "#{name}/#{test}/#{name}_#{test}.rb"

  def copy_licence
    if yes?("Use MIT license?")
      # Make a copy of the MITLICENSE file at the source root
      copy_file "MITLICENSE", "#{name}/MITLICENSE"
      say "Shame on you…", :red

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 %>

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".

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.