**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON
<https://guides.rubyonrails.org>.**

Rails Generators & Templates
============================

Rails generators and application templates are useful tools that can improve
your workflow by automatically creating boilerplate code. In this guide you will
learn:

* How to see which generators are available in your application.
* How to create a custom generator using templates.
* How Rails searches for generators before invoking them.
* How to customize Rails scaffolding by overriding generators and templates.
* How to configure fallbacks to override specific generators.
* How to use templates to create/customize Rails applications.
* How to use the Rails Template API to write your own reusable application
  templates.

--------------------------------------------------------------------------------

What are Generators?
--------------------

When you create an application using the `rails new` command, you're using a
Rails generator. Generators create specific files in your application and allow
automating boilerplate code. You can get a list of all available generators by
invoking `bin/rails generate` from within any Rails application:

```bash
$ rails new myapp
$ cd myapp
$ bin/rails generate
Usage:
  bin/rails generate GENERATOR [args] [options]

General options:
  -h, [--help]     # Print generator's options and usage
  -p, [--pretend]  # Run but do not make any changes
  -f, [--force]    # Overwrite files that already exist
  -s, [--skip]     # Skip files that already exist
  -q, [--quiet]    # Suppress status output

Please choose a generator below.

Rails:
  application_record
  authentication
  benchmark
  channel
  controller
  generator
  ...
SolidQueue:
  solid_queue:install

Stimulus:
  stimulus

TestUnit:
  test_unit:authentication
  test_unit:channel
  ...
```

NOTE: To create a Rails application we use the `rails` global command which uses
the version of Rails installed via `gem install rails`. When inside the
directory of your application, we use the `bin/rails` command which uses the
version of Rails bundled with the application.

You will get a list of all available generators along with usage instructions.
For example, you can run a generator with the `--pretend` (or `-p`) option to
get a sense of what a specific generator would do *without* actually making the
changes:

```bash
$ bin/rails generate model product name:string --pretend
      invoke  active_record
      create    db/migrate/20260407190300_create_products.rb
      create    app/models/product.rb
      invoke    test_unit
      create      test/models/product_test.rb
      create      test/fixtures/products.yml
```

None of the above files are actually created with the `--pretend` option.

TIP: The `--pretend` option can be handy to check the difference in files
generated by related generators before actually running them. For example,
`model` vs. `resource` generator.

To see a detailed description of a particular generator, invoke the generator
with the `--help` option. For example:

```bash
$ bin/rails generate scaffold --help
Usage:
  bin/rails generate scaffold NAME [field[:type][:index] field[:type][:index]] [options]
...
Description:
    Scaffolds an entire resource, from model and migration to controller and
    views, along with a full test suite. The resource is ready to use as a
    starting point for your RESTful, resource-oriented application.
...
Examples:
    `bin/rails generate scaffold post`
    `bin/rails generate scaffold post title:string body:text published:boolean`
    `bin/rails generate scaffold purchase amount:decimal tracking_id:integer:uniq`
    `bin/rails generate scaffold user email:uniq password:digest`
...
```

The `--help` output is a good resource to learn more about a particular
generator. It provides detailed usage instructions as well as examples.

Creating Your First Generator
-----------------------------

In addition to generators provided by Rails, you can also build custom
generators. Let's build a generator that creates an initializer file named
`hello_generator.rb` inside `config/initializers` folder. We will do this
manually first and then see how to do it using a `generator` command as well.

NOTE: Generators are built on top of [Thor][], which provides useful options
for parsing and an API for manipulating files.

The first step in manually creating a generator is to create a file named
`initializer_generator.rb` inside `lib/generators` with the following content:

```ruby
class InitializerGenerator < Rails::Generators::Base
  def create_initializer_file
    create_file "config/initializers/hello_generator.rb", <<~RUBY
      # Add hello_generator.rb file content here
    RUBY
  end
end
```

The name of our generator based on the file and Ruby class name is `initializer`
and it inherits from [`Rails::Generators::Base`][]. When a generator is invoked,
each public method in the generator is executed sequentially in the order that
it is defined. Our new generator is intentionally simple, it has only one method
definition.  The method invokes [`create_file`][], which will create a file at
the given destination with the given content.

To invoke our new generator, we run:

```bash
$ bin/rails generate initializer
```

This will create an empty file named `hello_generator.rb` within the
`config/initializers` folder.

Before we go on, let's check the description of our new generator:

```bash
$ bin/rails generate initializer --help
```

Rails is usually able to derive a good description if a generator is namespaced,
such as `ActiveRecord::Generators::ModelGenerator`, but not in this case. We can
solve this problem in two ways. The first way is to add a description by calling
[`desc`][] inside our generator:

```ruby#2
class InitializerGenerator < Rails::Generators::Base
  desc "This generator creates a file at config/initializers"
  def create_initializer_file
    create_file "config/initializers/hello_generator.rb", <<~RUBY
      # Add hello_generator.rb file content here
    RUBY
  end
end
```

Now we can see the description by invoking `--help` on the new generator.

The second way to add a description is by creating a file named `USAGE` in the
same directory as our generator. We are going to do that in the next step.

[Thor]:
  https://github.com/rails/thor
[`Rails::Generators::Base`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Base.html
[`Thor::Actions`]:
  https://www.rubydoc.info/gems/thor/Thor/Actions
[`create_file`]:
  https://www.rubydoc.info/gems/thor/Thor/Actions#create_file-instance_method
[`desc`]:
  https://www.rubydoc.info/gems/thor/Thor#desc-class_method

### Creating Generators by Using a Generator

Generators themselves have a generator that can create the necessary files in
the right locations. Let's remove our `InitializerGenerator` and use `bin/rails
generate generator` command to generate a new one:

```bash
$ rm lib/generators/initializer_generator.rb

$ bin/rails generate generator initializer
      create  lib/generators/initializer
      create  lib/generators/initializer/initializer_generator.rb
      create  lib/generators/initializer/USAGE
      create  lib/generators/initializer/templates
      invoke  test_unit
      create    test/lib/generators/initializer_generator_test.rb
```

This is the generator just created:

```ruby
# lib/generators/initializer/initializer_generator.rb
class InitializerGenerator < Rails::Generators::NamedBase
  source_root File.expand_path("templates", __dir__)
end
```

First, notice that the generator inherits from
[`Rails::Generators::NamedBase`][] instead of `Rails::Generators::Base`. This
means that our generator expects at least one argument, which will be the name
of the initializer and will be available to our code via `name`.

We can see that by checking the description of the new generator:

```bash
$ bin/rails generate initializer --help
Usage:
  bin/rails generate initializer NAME [options]
```

Also, notice that the generator has a class method called [`source_root`][].
This method points to the location of our template files. Template files are the
files that generators use as blueprints when creating new files in the
application. By default, they are in the `lib/generators/initializer/templates`
directory that was just created.

In order to understand how generator templates work, let's create the file
`lib/generators/initializer/templates/initializer.rb` with the following
content:

```ruby
# Add initialization content here
```

And let's change the generator to copy this template when invoked:

```ruby
class InitializerGenerator < Rails::Generators::NamedBase
  source_root File.expand_path("templates", __dir__)

  def copy_initializer_file
    copy_file "initializer.rb", "config/initializers/#{file_name}.rb"
  end
end
```

Now let's run our generator:

```bash
$ bin/rails generate initializer core_extensions
      create  config/initializers/core_extensions.rb

$ cat config/initializers/core_extensions.rb
# Add initialization content here
```

We see that [`copy_file`][] created `config/initializers/core_extensions.rb`
with the contents of our template. (The `file_name` method used in the
destination path is inherited from `Rails::Generators::NamedBase`.)

[`Rails::Generators::NamedBase`]:
  https://api.rubyonrails.org/classes/Rails/Generators/NamedBase.html
[`copy_file`]:
  https://www.rubydoc.info/gems/thor/Thor/Actions#copy_file-instance_method
[`source_root`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Base.html#method-c-source_root

### Generator Command Line Options

Generators can support command line options using [`class_option`][]. For
example:

```ruby
class InitializerGenerator < Rails::Generators::NamedBase
  class_option :scope, type: :string, default: "app"
end
```

Now our generator can be invoked with a `--scope` option:

```bash
$ bin/rails generate initializer theme --scope dashboard
```

This will override the default value "app" for the `--scope` option with
"dashboard". Option values are accessible in generator methods via
[`options`][]:

```ruby
def copy_initializer_file
  @scope = options["scope"]
  copy_file "initializer.rb", "config/initializers/#{@scope}/#{file_name}.rb"
end
```

Now with the scope option set, the file `theme.rb` is generated at
`config/initializers/dashboard/`.

[`class_option`]:
  https://www.rubydoc.info/gems/thor/Thor/Base/ClassMethods#class_option-instance_method
[`options`]:
  https://www.rubydoc.info/gems/thor/Thor/Base#options-instance_method

Generator Resolution
--------------------

When resolving a generator's name, Rails looks for the generator using multiple
file names. For example, when you run `bin/rails generate initializer
core_extensions`, Rails tries to load each of the following files, in order,
until one is found:

* `rails/generators/initializer/initializer_generator.rb`
* `generators/initializer/initializer_generator.rb`
* `rails/generators/initializer_generator.rb`
* `generators/initializer_generator.rb`

If none of these are found, an error will be raised.

We put our generator in the application's `lib/` directory because that
directory is in `$LOAD_PATH` (Ruby's list of directories searched when loading
files), thus allowing Rails to find and load the generator files.

NOTE: `$LOAD_PATH` is initialized by Ruby and expanded by Bundler and Rails at
boot time. Bundler adds each gem's `lib/` directory, and Rails adds your
application's `lib/` directory, which is why generators placed there are
findable. You can inspect the full load path by running `bin/rails runner 'puts
$LOAD_PATH'`. You can modify it with `config.autoload_paths` in your
`application.rb` file.

Overriding Rails Generators and Templates
-----------------------------------------

It's possible to override the built-in Rails generators and configure them via
[`config.generators`][]. As your Rails application grows, you may want to add
your own methods to generated controllers, for example, or change the format of
generated views.

As an example of how to override a built-in generator, let's take a closer look
at how the scaffold generator works.

```bash
$ bin/rails generate scaffold User name:string
      invoke  active_record
      create    db/migrate/20230518000000_create_users.rb
      create    app/models/user.rb
      invoke    test_unit
      create      test/models/user_test.rb
      create      test/fixtures/users.yml
      invoke  resource_route
       route    resources :users
      invoke  scaffold_controller
      create    app/controllers/users_controller.rb
      invoke    erb
      create      app/views/users
      create      app/views/users/index.html.erb
      create      app/views/users/edit.html.erb
      create      app/views/users/show.html.erb
      create      app/views/users/new.html.erb
      create      app/views/users/_form.html.erb
      create      app/views/users/_user.html.erb
      invoke    resource_route
      invoke    test_unit
      create      test/controllers/users_controller_test.rb
      create      test/system/users_test.rb
      invoke    helper
      create      app/helpers/users_helper.rb
      invoke      test_unit
      invoke    jbuilder
      create      app/views/users/index.json.jbuilder
      create      app/views/users/show.json.jbuilder
```

From the output, we can see that the scaffold generator invokes other
generators, such as the `scaffold_controller` generator. And some of those
generators invoke other generators too. In particular, the `scaffold_controller`
generator invokes the `helper` generator.

Let's see how to override the built-in `helper` generator with a new generator.
We'll name the new generator `my_helper`. We create this generator using the
`generator` command inside `lib/generators/rails`:

```bash
$ bin/rails generate generator rails/my_helper
      create  lib/generators/rails/my_helper
      create  lib/generators/rails/my_helper/my_helper_generator.rb
      create  lib/generators/rails/my_helper/USAGE
      create  lib/generators/rails/my_helper/templates
      invoke  test_unit
      create    test/lib/generators/rails/my_helper_generator_test.rb
```

And in the file `my_helper_generator.rb`, we'll define the generator as:

```ruby
# lib/generators/rails/my_helper/my_helper_generator.rb
class Rails::MyHelperGenerator < Rails::Generators::NamedBase
  def create_helper_file
    create_file "app/helpers/#{file_name}_helper.rb", <<~RUBY
      module #{class_name}Helper
        # I'm helping!
      end
    RUBY
  end
end
```

Finally, we need to tell Rails to use the `my_helper` generator instead of the
built-in `helper` generator. For that we use `config.generators`. In
`config/application.rb`, let's add:

```ruby
config.generators do |g|
  g.helper :my_helper
end
```

Now if we run the scaffold generator again, we see the `my_helper` generator in
action:

```bash#5
$ bin/rails generate scaffold Article body:text
      ...
      invoke  scaffold_controller
      ...
      invoke    my_helper
      create      app/helpers/articles_helper.rb
      ...
```

NOTE: You may notice that the output for the built-in `helper` generator
includes "invoke test_unit", whereas the output for `my_helper` does not.
Although the `helper` generator does not generate tests by default, it does
provide a hook to do so using [`hook_for`][]. We can do the same by including
`hook_for :test_framework, as: :helper` in the `MyHelperGenerator` class. See
the [`hook_for`][] documentation for more information.

[`config.generators`]:
  configuring.html#configuring-generators
[`hook_for`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Base.html#method-c-hook_for

### Overriding Generators with Fallbacks

Another way to override specific generators is by using _fallbacks_. A fallback
allows a generator namespace to delegate to another generator namespace when a
matching generator is not found.

For example, let's say we want to override the `test_unit:model` generator with
our own `my_test_unit:model` generator, but we don't want to replace all of the
other `test_unit:*` generators such as `test_unit:controller`. Instead of
implementing every generator in the `my_test_unit` namespace, we can configure
`my_test_unit` to fall back to `test_unit` for any generator we haven't
explicitly defined.

First, we create the `my_test_unit:model` generator in
`lib/generators/my_test_unit/model/model_generator.rb`:

```ruby
module MyTestUnit
  class ModelGenerator < Rails::Generators::NamedBase
    source_root File.expand_path("templates", __dir__)

    def do_different_stuff
      say "Doing different stuff..."
    end
  end
end
```

NOTE: Because `my_test_unit` is a custom namespace rather than an override of a
Rails built-in generator, we place it in `lib/generators/my_test_unit/` rather
than `lib/generators/rails/`. Rails will find it via the normal load path
lookup. We'll also need to register it as the `test_framework` via
`config.generators`, which we'll do in the next step.

Next, we use `config.generators` to configure the `test_framework` generator as
`my_test_unit`, but we also configure a fallback such that any missing
`my_test_unit:*` generators resolve to `test_unit:*`:

```ruby
config.generators do |g|
  g.test_framework :my_test_unit, fixture: false
  g.fallbacks[:my_test_unit] = :test_unit
end
```

Now when we run the scaffold generator, we see that `my_test_unit` has replaced
`test_unit`, but only the model tests have been affected:

```bash
$ bin/rails generate scaffold Comment body:text
      invoke  active_record
      create    db/migrate/20230518000000_create_comments.rb
      create    app/models/comment.rb
      invoke    my_test_unit
    Doing different stuff...
      invoke  resource_route
       route    resources :comments
      invoke  scaffold_controller
      create    app/controllers/comments_controller.rb
      invoke    erb
      create      app/views/comments
      create      app/views/comments/index.html.erb
      create      app/views/comments/edit.html.erb
      create      app/views/comments/show.html.erb
      create      app/views/comments/new.html.erb
      create      app/views/comments/_form.html.erb
      create      app/views/comments/_comment.html.erb
      invoke    resource_route
      invoke    my_test_unit
      create      test/controllers/comments_controller_test.rb
      create      test/system/comments_test.rb
      invoke    helper
      create      app/helpers/comments_helper.rb
      invoke      my_test_unit
      invoke    jbuilder
      create      app/views/comments/index.json.jbuilder
      create      app/views/comments/show.json.jbuilder
```

NOTE: Notice that the model invocation of `my_test_unit` only prints "Doing
different stuff..." and creates no test file, because our custom generator
doesn't create one. The controller and helper invocations of `my_test_unit` fall
back to `test_unit`, which is why `test/controllers/comments_controller_test.rb`
is still generated as normal.

### Overriding Generator Templates

When resolving generator template files, Rails looks first in the application's
`lib/templates/` directory, then falls back to the generator's own `source_root`
directory. This means we can override the templates used by Rails' built-in
generators by placing our own versions in `lib/templates/`. For example, we
could override the [scaffold controller template][scaffold_controller_template]
or the [scaffold view templates][scaffold_view_templates].

To see this in action, let's create a
`lib/templates/erb/scaffold/index.html.erb.tt` file with the content shown
below. The extra `.tt` extension tells Rails that the file is a generator
template that needs to be processed by Thor first (The `.tt` stands for "thor
template").

```erb
<%%= @<%= plural_table_name %>.count %> <%= human_name.pluralize %>
```

The template is an ERB template that renders _another_ ERB template. So any `<%`
that should appear in the _resulting_ template must be escaped as `<%%` in the
_generator_ template.

Now when you run Rails' built-in scaffold generator:

```bash
$ bin/rails generate scaffold Post title:string
      ...
      create      app/views/posts/index.html.erb
      ...
```

The content of `app/views/posts/index.html.erb` is:

```erb
<%= @posts.count %> Posts
```

[scaffold_controller_template]:
  https://github.com/rails/rails/blob/main/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb.tt
[scaffold_view_templates]:
  https://github.com/rails/rails/tree/main/railties/lib/rails/generators/erb/scaffold/templates

Application Templates
---------------------

Application templates are a little different from generators. While generators
add files to an existing Rails application (models, views, etc.), templates are
used to automate the setup of a new Rails application. Templates are Ruby
scripts (typically named `template.rb`) that customize new Rails applications
right after they are generated.

Let's see how to use a template while creating a new Rails application.

### Creating and Using Templates

Let's start with a sample template Ruby script. The below template adds Devise
to the `Gemfile` after asking the user and also allows the user to name the
Devise user model. After `bundle install` has been run, the template runs the
Devise generators and also runs migrations. Finally, the template does `git add`
and `git commit`.

```ruby
# template.rb
if yes?("Would you like to install Devise?")
  gem "devise"
  devise_model = ask("What would you like the user model to be called?", default: "User")
end

after_bundle do
  if devise_model
    generate "devise:install"
    generate "devise", devise_model
    rails_command "db:migrate"
  end

  git add: ".", commit: %(-m 'Initial commit')
end
```

To apply this template while creating a new Rails application, you need to
provide the location of the template using the `-m` option:

```bash
$ rails new blog -m ~/template.rb
```

The above will create a new Rails application called `blog` that has Devise gem
configured.

You can also apply templates to an existing Rails application by using
`app:template` command. The location of the template needs to be passed in via
the `LOCATION` environment variable:

```bash
$ bin/rails app:template LOCATION=~/template.rb
```

Templates don't have to be stored locally, you can also specify a URL instead of
a path:

```bash
$ rails new blog -m https://example.com/template.rb
$ bin/rails app:template LOCATION=https://example.com/template.rb
```

WARNING: Caution should be taken when executing remote scripts from third
parties. Since the template is a plain Ruby script, it can easily contain code
that compromises your local machine (such as download a virus, delete files or
upload your private files to a server).

The above `template.rb` file uses helper methods such as `after_bundle` and
`rails_command` and also adds user interactivity with methods like `yes?`. All
of these methods are part of the [Rails Template
API][`Rails::Generators::Actions`]. The following sections shows how to use
more of these methods with examples.

Rails Generators API
--------------------

Generators and the template Ruby scripts have access to several helper methods
using a [DSL][] (Domain
Specific Language). These methods are part of the Rails Generators API and you
can find more details at [`Thor::Actions`][] and [`Rails::Generators::Actions`][] API documentation.

Here's another example of a typical Rails template that scaffolds a model, runs
migrations, and commits the changes with git:

```ruby
# template.rb
generate(:scaffold, "person name:string")
route "root to: 'people#index'"
rails_command("db:migrate")

after_bundle do
  git :init
  git add: "."
  git commit: %Q{ -m 'Initial commit' }
end
```

NOTE: All code snippets in the examples below can be used in a template file,
such as the `template.rb` file above.

[DSL]:
  https://en.wikipedia.org/wiki/Domain-specific_language

### add_source

The [`add_source`][] method adds the given source to the generated application's
`Gemfile`.

```ruby
add_source "https://rubygems.org"
```

If a block is given, gem entries in the block are wrapped into the source group.
For example, if you need to source a gem from `"http://gems.github.com"`:

```ruby
add_source "http://gems.github.com/" do
  gem "rspec-rails"
end
```

### after_bundle

The [`after_bundle`][] method registers a callback to be executed after the gems
are bundled. For example, it would make sense to run the "install" command for
`tailwindcss-rails` and `devise` only after those gems are bundled:

```ruby
# Install gems
after_bundle do
  # Install TailwindCSS
  rails_command "tailwindcss:install"

  # Install Devise
  generate "devise:install"
end
```

The callbacks get executed even if `--skip-bundle` has been passed.

### environment

The [`environment`][] method adds a line inside the `Application` class for
`config/application.rb`. If `options[:env]` is specified, the line is appended
to the corresponding file in `config/environments`.

```ruby
environment 'config.action_mailer.default_url_options = {host: "http://yourwebsite.example.com"}', env: "production"
```

The above will add the config line to `config/environments/production.rb`.

### gem

The [`gem`][] helper adds an entry for the given gem to the generated
application's `Gemfile`.

For example, if your application depends on the gems `devise` and
`tailwindcss-rails`:

```ruby
gem "devise"
gem "tailwindcss-rails"
```

Note that this method only adds the gem to the `Gemfile`, it does not install
the gem.

You can also specify an exact version:

```ruby
gem "devise", "~> 4.9.4"
```

And you can also add comments that will be added to the `Gemfile`:

```ruby
gem "devise", comment: "Add devise for authentication."
```

### gem_group

The [`gem_group`][] helper wraps gem entries inside a group. For example, to
load `rspec-rails` only in the `development` and `test` groups:

```ruby
gem_group :development, :test do
  gem "rspec-rails"
end
```

### generate

You can even call a generator from inside a `template.rb` with the
[`generate`][] method. The following runs the `scaffold` rails generator with
the given arguments:

```ruby
generate(:scaffold, "person", "name:string", "address:text", "age:number")
```

### git

Rails templates let you run any git command with the [`git`][] helper:

```ruby
git :init
git add: "."
git commit: "-a -m 'Initial commit'"
```

### initializer, vendor, lib, file

The [`initializer`][] helper method adds an initializer to the generated
application's `config/initializers` directory.

After adding the below to the `template.rb` file, you can use `Object#not_nil?`
and `Object#not_blank?` in your application:

```ruby
initializer "not_methods.rb", <<-CODE
  class Object
    def not_nil?
      !nil?
    end

    def not_blank?
      !blank?
    end
  end
CODE
```

Similarly, the [`lib`][] method creates a file in the `lib/` directory and
[`vendor`][] method creates a file in the `vendor/` directory.

There is also a `file` method (which is an alias for [`create_file`][]), which
accepts a relative path from `Rails.root` and creates all the directories and
files needed:

```ruby
file "app/components/foo.rb", <<-CODE
  class Foo
  end
CODE
```

The above will create the `app/components` directory and put `foo.rb` in there.

### rakefile

The [`rakefile`][] method creates a new Rake file under `lib/tasks` with the
given tasks:

```ruby
rakefile("bootstrap.rake") do
  <<-TASK
    namespace :boot do
      task :strap do
        puts "I like boots!"
      end
    end
  TASK
end
```

The above creates `lib/tasks/bootstrap.rake` with a `boot:strap` rake task.

### run

The [`run`][] method executes an arbitrary command. Let's say you want to remove
the `README.rdoc` file:

```ruby
run "rm README.rdoc"
```

### rails_command

You can run the Rails commands in the generated application with the
[`rails_command`][] helper. Let's say you want to migrate the database at some
point in the template ruby script:

```ruby
rails_command "db:migrate"
```

Commands can be run with a different Rails environment:

```ruby
rails_command "db:migrate", env: "production"
```

You can also run commands that should abort application generation if they fail:

```ruby
rails_command "db:migrate", abort_on_failure: true
```

### route

The [`route`][] method adds an entry to the `config/routes.rb` file. To make
`PeopleController#index` the default page for the application, we can add:

```ruby
route "root to: 'person#index'"
```

There are also many helper methods that can manipulate the local file system,
such as [`copy_file`][], [`create_file`][], [`insert_into_file`][], and
[`inside`][]. You can see the [Thor API documentation][thor_api] for details.
Here is an example of one such method:

[thor_api]:
  https://www.rubydoc.info/gems/thor/Thor/Actions

### inside

This [`inside`][] method enables you to run a command from a given directory.
For example, if you have a copy of edge rails that you wish to symlink from your
new apps, you can do this:

```ruby
inside("vendor") do
  run "ln -s ~/my-forks/rails rails"
end
```

There are also methods that allow you to interact with the user from the Ruby
template, such as [`ask`][], [`yes`][], and [`no`][]. You can learn about all
user interactivity methods in the [Thor Shell documentation][thor_shell]. Let's
see examples of using `ask`, `yes?` and `no?`:

[thor_shell]:
  https://www.rubydoc.info/gems/thor/Thor/Shell/Basic

### ask

The [`ask`][] methods allows you to get feedback from the user and use it in
your templates. Let's say you want your user to name the new shiny library
you're adding:

```ruby
lib_name = ask("What do you want to call the shiny library?")
lib_name << ".rb" unless lib_name.index(".rb")

lib lib_name, <<-CODE
  class Shiny
  end
CODE
```

### yes? or no?

These methods let you ask questions from templates and decide the flow based on
the user's answer. Let's say you want to prompt the user to run migrations:

```ruby
rails_command("db:migrate") if yes?("Run database migrations?")
# no? questions acts the opposite of yes?
```

Testing Generators
------------------

Rails provides testing helper methods via
[`Rails::Generators::Testing::Behavior`][], such as:

* [`run_generator`][]

If running tests against generators you will need to set
`RAILS_LOG_TO_STDOUT=true` in order for debugging tools to work.

```sh
RAILS_LOG_TO_STDOUT=true ./bin/test test/generators/actions_test.rb
```

In addition to those, Rails also provides additional assertions via
[`Rails::Generators::Testing::Assertions`][].

[`Rails::Generators::Actions`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Actions.html
[`environment`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Actions.html#method-i-environment
[`gem`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Actions.html#method-i-gem
[`generate`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Actions.html#method-i-generate
[`git`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Actions.html#method-i-git
[`gsub_file`]:
  https://www.rubydoc.info/gems/thor/Thor/Actions#gsub_file-instance_method
[`initializer`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Actions.html#method-i-initializer
[`insert_into_file`]:
  https://www.rubydoc.info/gems/thor/Thor/Actions#insert_into_file-instance_method
[`inside`]:
  https://www.rubydoc.info/gems/thor/Thor/Actions#inside-instance_method
[`lib`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Actions.html#method-i-lib
[`rails_command`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Actions.html#method-i-rails_command
[`rake`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Actions.html#method-i-rake
[`route`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Actions.html#method-i-route
[`Rails::Generators::Testing::Behavior`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Testing/Behavior.html
[`run_generator`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Testing/Behavior.html#method-i-run_generator
[`Rails::Generators::Testing::Assertions`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Testing/Assertions.html
[`add_source`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Actions.html#method-i-add_source
[`after_bundle`]:
  https://api.rubyonrails.org/classes/Rails/Generators/AppGenerator.html#method-i-after_bundle
[`gem_group`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Actions.html#method-i-gem_group
[`vendor`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Actions.html#method-i-vendor
[`rakefile`]:
  https://api.rubyonrails.org/classes/Rails/Generators/Actions.html#method-i-rakefile
[`run`]:
  https://www.rubydoc.info/gems/thor/Thor/Actions#run-instance_method
[`copy_file`]:
  https://www.rubydoc.info/gems/thor/Thor/Actions#copy_file-instance_method
[`create_file`]:
  https://www.rubydoc.info/gems/thor/Thor/Actions#create_file-instance_method
[`ask`]:
  https://www.rubydoc.info/gems/thor/Thor/Shell/Basic#ask-instance_method
[`yes`]:
  https://www.rubydoc.info/gems/thor/Thor/Shell/Basic#yes%3F-instance_method
[`no`]:
  https://www.rubydoc.info/gems/thor/Thor/Shell/Basic#no%3F-instance_method

