generators.md 24.7 KB
Newer Older
1
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.**
X
Xavier Noria 已提交
2

3 4
Creating and Customizing Rails Generators & Templates
=====================================================
P
Pratik Naik 已提交
5

X
Xavier Noria 已提交
6
Rails generators are an essential tool if you plan to improve your workflow. With this guide you will learn how to create generators and customize existing ones.
P
Pratik Naik 已提交
7

8
After reading this guide, you will know:
P
Pratik Naik 已提交
9

10 11 12
* How to see which generators are available in your application.
* How to create a generator using templates.
* How Rails searches for generators before invoking them.
13
* How Rails internally generates Rails code from the templates.
14 15 16 17
* How to customize your scaffold by creating new generators.
* How to customize your scaffold by changing generator templates.
* How to use fallbacks to avoid overwriting a huge set of generators.
* How to create an application template.
P
Pratik Naik 已提交
18

19
--------------------------------------------------------------------------------
P
Pratik Naik 已提交
20

21 22
First Contact
-------------
P
Pratik Naik 已提交
23

24
When you create an application using the `rails` command, you are in fact using a Rails generator. After that, you can get a list of all available generators by just invoking `bin/rails generate`:
P
Pratik Naik 已提交
25

P
Prem Sichanugrist 已提交
26
```bash
27
$ rails new myapp
P
Pratik Naik 已提交
28
$ cd myapp
29
$ bin/rails generate
30
```
P
Pratik Naik 已提交
31

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

E
EzraShimon 已提交
34
You will get a list of all generators that come with Rails. If you need a detailed description of the helper generator, for example, you can simply do:
P
Pratik Naik 已提交
35

P
Prem Sichanugrist 已提交
36
```bash
37
$ bin/rails generate helper --help
38
```
P
Pratik Naik 已提交
39

40 41
Creating Your First Generator
-----------------------------
P
Pratik Naik 已提交
42

43
Since Rails 3.0, generators are built on top of [Thor](https://github.com/erikhuda/thor). Thor provides powerful options for parsing and a great API for manipulating files. For instance, let's build a generator that creates an initializer file named `initializer.rb` inside `config/initializers`.
P
Pratik Naik 已提交
44

45
The first step is to create a file at `lib/generators/initializer_generator.rb` with the following content:
P
Pratik Naik 已提交
46

47
```ruby
P
Pratik Naik 已提交
48 49 50 51 52
class InitializerGenerator < Rails::Generators::Base
  def create_initializer_file
    create_file "config/initializers/initializer.rb", "# Add initialization content here"
  end
end
53
```
P
Pratik Naik 已提交
54

J
Juanjo Bazán 已提交
55
NOTE: `create_file` is a method provided by `Thor::Actions`. Documentation for `create_file` and other Thor methods can be found in [Thor's documentation](https://rdoc.info/github/erikhuda/thor/master/Thor/Actions.html)
56

57
Our new generator is quite simple: it inherits from `Rails::Generators::Base` and has one method definition. When a generator is invoked, each public method in the generator is executed sequentially in the order that it is defined. Finally, we invoke the `create_file` method that will create a file at the given destination with the given content. If you are familiar with the Rails Application Templates API, you'll feel right at home with the new generators API.
P
Pratik Naik 已提交
58 59 60

To invoke our new generator, we just need to do:

P
Prem Sichanugrist 已提交
61
```bash
62
$ bin/rails generate initializer
63
```
P
Pratik Naik 已提交
64 65 66

Before we go on, let's see our brand new generator description:

P
Prem Sichanugrist 已提交
67
```bash
68
$ bin/rails generate initializer --help
69
```
P
Pratik Naik 已提交
70

71
Rails is usually able to generate good descriptions if a generator is namespaced, as `ActiveRecord::Generators::ModelGenerator`, but not in this particular case. We can solve this problem in two ways. The first one is calling `desc` inside our generator:
P
Pratik Naik 已提交
72

73
```ruby
P
Pratik Naik 已提交
74 75 76 77 78 79
class InitializerGenerator < Rails::Generators::Base
  desc "This generator creates an initializer file at config/initializers"
  def create_initializer_file
    create_file "config/initializers/initializer.rb", "# Add initialization content here"
  end
end
80
```
P
Pratik Naik 已提交
81

82
Now we can see the new 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.
P
Pratik Naik 已提交
83

84 85
Creating Generators with Generators
-----------------------------------
P
Pratik Naik 已提交
86

X
Xavier Noria 已提交
87
Generators themselves have a generator:
P
Pratik Naik 已提交
88

P
Prem Sichanugrist 已提交
89
```bash
90
$ bin/rails generate generator initializer
P
Pratik Naik 已提交
91 92 93 94
      create  lib/generators/initializer
      create  lib/generators/initializer/initializer_generator.rb
      create  lib/generators/initializer/USAGE
      create  lib/generators/initializer/templates
95 96
      invoke  test_unit
      create    test/lib/generators/initializer_generator_test.rb
97
```
P
Pratik Naik 已提交
98

X
Xavier Noria 已提交
99
This is the generator just created:
P
Pratik Naik 已提交
100

101
```ruby
P
Pratik Naik 已提交
102
class InitializerGenerator < Rails::Generators::NamedBase
103
  source_root File.expand_path('templates', __dir__)
P
Pratik Naik 已提交
104
end
105
```
P
Pratik Naik 已提交
106

107
First, notice that we are inheriting 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 in our code in the variable `name`.
P
Pratik Naik 已提交
108 109 110

We can see that by invoking the description of this new generator (don't forget to delete the old generator file):

P
Prem Sichanugrist 已提交
111
```bash
112
$ bin/rails generate initializer --help
P
Pratik Naik 已提交
113
Usage:
114
  bin/rails generate initializer NAME [options]
115
```
P
Pratik Naik 已提交
116

117
We can also see that our new generator has a class method called `source_root`. This method points to where our generator templates will be placed, if any, and by default it points to the created directory `lib/generators/initializer/templates`.
X
Xavier Noria 已提交
118

119
In order to understand what a generator template means, let's create the file `lib/generators/initializer/templates/initializer.rb` with the following content:
P
Pratik Naik 已提交
120

121
```ruby
P
Pratik Naik 已提交
122
# Add initialization content here
123
```
P
Pratik Naik 已提交
124 125 126

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

127
```ruby
P
Pratik Naik 已提交
128
class InitializerGenerator < Rails::Generators::NamedBase
129
  source_root File.expand_path('templates', __dir__)
P
Pratik Naik 已提交
130 131 132 133 134

  def copy_initializer_file
    copy_file "initializer.rb", "config/initializers/#{file_name}.rb"
  end
end
135
```
P
Pratik Naik 已提交
136 137 138

And let's execute our generator:

P
Prem Sichanugrist 已提交
139
```bash
140
$ bin/rails generate initializer core_extensions
141
```
P
Pratik Naik 已提交
142

143
We can see that now an initializer named core_extensions was created at `config/initializers/core_extensions.rb` with the contents of our template. That means that `copy_file` copied a file in our source root to the destination path we gave. The method `file_name` is automatically created when we inherit from `Rails::Generators::NamedBase`.
P
Pratik Naik 已提交
144

145
The methods that are available for generators are covered in the [final section](#generator-methods) of this guide.
146

147 148
Generators Lookup
-----------------
P
Pratik Naik 已提交
149

150
When you run `bin/rails generate initializer core_extensions` Rails requires these files in turn until one is found:
P
Pratik Naik 已提交
151

152
```
J
José Valim 已提交
153 154 155 156
rails/generators/initializer/initializer_generator.rb
generators/initializer/initializer_generator.rb
rails/generators/initializer_generator.rb
generators/initializer_generator.rb
157
```
P
Pratik Naik 已提交
158

X
Xavier Noria 已提交
159 160
If none is found you get an error message.

161
INFO: The examples above put files under the application's `lib` because said directory belongs to `$LOAD_PATH`.
P
Pratik Naik 已提交
162

163 164
Customizing Your Workflow
-------------------------
P
Pratik Naik 已提交
165

166
Rails own generators are flexible enough to let you customize scaffolding. They can be configured in `config/application.rb`, these are some defaults:
P
Pratik Naik 已提交
167

168
```ruby
P
Pratik Naik 已提交
169 170 171
config.generators do |g|
  g.orm             :active_record
  g.template_engine :erb
172
  g.test_framework  :test_unit, fixture: true
P
Pratik Naik 已提交
173
end
174
```
P
Pratik Naik 已提交
175

176
Before we customize our workflow, let's first see what our scaffold looks like:
P
Pratik Naik 已提交
177

P
Prem Sichanugrist 已提交
178
```bash
179
$ bin/rails generate scaffold User name:string
P
Pratik Naik 已提交
180
      invoke  active_record
181
      create    db/migrate/20130924151154_create_users.rb
P
Pratik Naik 已提交
182 183
      create    app/models/user.rb
      invoke    test_unit
M
Mike Moore 已提交
184
      create      test/models/user_test.rb
P
Pratik Naik 已提交
185
      create      test/fixtures/users.yml
186 187
      invoke  resource_route
       route    resources :users
P
Pratik Naik 已提交
188 189 190 191 192 193 194 195 196 197
      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
      invoke    test_unit
M
Mike Moore 已提交
198
      create      test/controllers/users_controller_test.rb
P
Pratik Naik 已提交
199 200
      invoke    helper
      create      app/helpers/users_helper.rb
201 202 203
      invoke    jbuilder
      create      app/views/users/index.json.jbuilder
      create      app/views/users/show.json.jbuilder
204 205 206
      invoke  test_unit
      create    test/application_system_test_case.rb
      create    test/system/users_test.rb
207 208
      invoke  assets
      invoke    scss
209
      create      app/assets/stylesheets/users.scss
210
      invoke  scss
211
      create    app/assets/stylesheets/scaffolds.scss
212
```
P
Pratik Naik 已提交
213

X
Xavier Noria 已提交
214
Looking at this output, it's easy to understand how generators work in Rails 3.0 and above. The scaffold generator doesn't actually generate anything, it just invokes others to do the work. This allows us to add/replace/remove any of those invocations. For instance, the scaffold generator invokes the scaffold_controller generator, which invokes erb, test_unit and helper generators. Since each generator has a single responsibility, they are easy to reuse, avoiding code duplication.
P
Pratik Naik 已提交
215

216 217 218 219 220 221 222 223
If we want to avoid generating the default `app/assets/stylesheets/scaffolds.scss` file when scaffolding a new resource we can disable `scaffold_stylesheet`:

```ruby
  config.generators do |g|
    g.scaffold_stylesheet false
  end
```

224
The next customization on the workflow will be to stop generating stylesheet and test fixture files for scaffolds altogether. We can achieve that by changing our configuration to the following:
P
Pratik Naik 已提交
225

226
```ruby
P
Pratik Naik 已提交
227 228 229
config.generators do |g|
  g.orm             :active_record
  g.template_engine :erb
230
  g.test_framework  :test_unit, fixture: false
P
Pratik Naik 已提交
231 232
  g.stylesheets     false
end
233
```
P
Pratik Naik 已提交
234

A
Anthony Crumley 已提交
235
If we generate another resource with the scaffold generator, we can see that stylesheet, JavaScript, and fixture files are not created anymore. If you want to customize it further, for example to use DataMapper and RSpec instead of Active Record and TestUnit, it's just a matter of adding their gems to your application and configuring your generators.
P
Pratik Naik 已提交
236

237
To demonstrate this, we are going to create a new helper generator that simply adds some instance variable readers. First, we create a generator within the rails namespace, as this is where rails searches for generators used as hooks:
P
Pratik Naik 已提交
238

P
Prem Sichanugrist 已提交
239
```bash
240
$ bin/rails generate generator rails/my_helper
241 242 243 244
      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
245 246
      invoke  test_unit
      create    test/lib/generators/rails/my_helper_generator_test.rb
247
```
P
Pratik Naik 已提交
248

249 250 251
After that, we can delete both the `templates` directory and the `source_root`
class method call from our new generator, because we are not going to need them.
Add the method below, so our generator looks like the following:
P
Pratik Naik 已提交
252

253
```ruby
254
# lib/generators/rails/my_helper/my_helper_generator.rb
255
class Rails::MyHelperGenerator < Rails::Generators::NamedBase
P
Pratik Naik 已提交
256
  def create_helper_file
257
    create_file "app/helpers/#{file_name}_helper.rb", <<-FILE
P
Pratik Naik 已提交
258 259 260 261 262 263
module #{class_name}Helper
  attr_reader :#{plural_name}, :#{plural_name.singularize}
end
    FILE
  end
end
264
```
P
Pratik Naik 已提交
265

266
We can try out our new generator by creating a helper for products:
P
Pratik Naik 已提交
267

P
Prem Sichanugrist 已提交
268
```bash
269
$ bin/rails generate my_helper products
270
      create  app/helpers/products_helper.rb
271
```
P
Pratik Naik 已提交
272

273
And it will generate the following helper file in `app/helpers`:
P
Pratik Naik 已提交
274

275
```ruby
X
Xavier Noria 已提交
276 277
module ProductsHelper
  attr_reader :products, :product
P
Pratik Naik 已提交
278
end
279
```
P
Pratik Naik 已提交
280

281
Which is what we expected. We can now tell scaffold to use our new helper generator by editing `config/application.rb` once again:
P
Pratik Naik 已提交
282

283
```ruby
P
Pratik Naik 已提交
284 285 286
config.generators do |g|
  g.orm             :active_record
  g.template_engine :erb
287
  g.test_framework  :test_unit, fixture: false
P
Pratik Naik 已提交
288 289 290
  g.stylesheets     false
  g.helper          :my_helper
end
291
```
P
Pratik Naik 已提交
292

X
Xavier Noria 已提交
293
and see it in action when invoking the generator:
P
Pratik Naik 已提交
294

P
Prem Sichanugrist 已提交
295
```bash
296
$ bin/rails generate scaffold Article body:text
P
Pratik Naik 已提交
297 298
      [...]
      invoke    my_helper
299
      create      app/helpers/articles_helper.rb
300
```
P
Pratik Naik 已提交
301 302 303

We can notice on the output that our new helper was invoked instead of the Rails default. However one thing is missing, which is tests for our new generator and to do that, we are going to reuse old helpers test generators.

304
Since Rails 3.0, this is easy to do due to the hooks concept. Our new helper does not need to be focused in one specific test framework, it can simply provide a hook and a test framework just needs to implement this hook in order to be compatible.
P
Pratik Naik 已提交
305

X
Xavier Noria 已提交
306
To do that, we can change the generator this way:
P
Pratik Naik 已提交
307

308
```ruby
309
# lib/generators/rails/my_helper/my_helper_generator.rb
310
class Rails::MyHelperGenerator < Rails::Generators::NamedBase
P
Pratik Naik 已提交
311
  def create_helper_file
312
    create_file "app/helpers/#{file_name}_helper.rb", <<-FILE
P
Pratik Naik 已提交
313 314 315 316 317 318 319 320
module #{class_name}Helper
  attr_reader :#{plural_name}, :#{plural_name.singularize}
end
    FILE
  end

  hook_for :test_framework
end
321
```
P
Pratik Naik 已提交
322

323
Now, when the helper generator is invoked and TestUnit is configured as the test framework, it will try to invoke both `Rails::TestUnitGenerator` and `TestUnit::MyHelperGenerator`. Since none of those are defined, we can tell our generator to invoke `TestUnit::Generators::HelperGenerator` instead, which is defined since it's a Rails generator. To do that, we just need to add:
P
Pratik Naik 已提交
324

325
```ruby
V
Vijay Dev 已提交
326
# Search for :helper instead of :my_helper
327
hook_for :test_framework, as: :helper
328
```
P
Pratik Naik 已提交
329 330 331

And now you can re-run scaffold for another resource and see it generating tests as well!

332 333
Customizing Your Workflow by Changing Generators Templates
----------------------------------------------------------
P
Pratik Naik 已提交
334

335
In the step above we simply wanted to add a line to the generated helper, without adding any extra functionality. There is a simpler way to do that, and it's by replacing the templates of already existing generators, in that case `Rails::Generators::HelperGenerator`.
P
Pratik Naik 已提交
336

337
In Rails 3.0 and above, generators don't just look in the source root for templates, they also search for templates in other paths. And one of them is `lib/templates`. Since we want to customize `Rails::Generators::HelperGenerator`, we can do that by simply making a template copy inside `lib/templates/rails/helper` with the name `helper.rb`. So let's create that file with the following content:
P
Pratik Naik 已提交
338

339
```erb
P
Pratik Naik 已提交
340
module <%= class_name %>Helper
M
manishval 已提交
341
  attr_reader :<%= plural_name %>, :<%= plural_name.singularize %>
P
Pratik Naik 已提交
342
end
343
```
P
Pratik Naik 已提交
344

345
and revert the last change in `config/application.rb`:
P
Pratik Naik 已提交
346

347
```ruby
P
Pratik Naik 已提交
348 349 350
config.generators do |g|
  g.orm             :active_record
  g.template_engine :erb
351
  g.test_framework  :test_unit, fixture: false
P
Pratik Naik 已提交
352 353
  g.stylesheets     false
end
354
```
P
Pratik Naik 已提交
355

356
If you generate another resource, you can see that we get exactly the same result! This is useful if you want to customize your scaffold templates and/or layout by just creating `edit.html.erb`, `index.html.erb` and so on inside `lib/templates/erb/scaffold`.
P
Pratik Naik 已提交
357

J
Jon Atack 已提交
358 359 360 361 362
Scaffold templates in Rails frequently use ERB tags; these tags need to be
escaped so that the generated output is valid ERB code.

For example, the following escaped ERB tag would be needed in the template
(note the extra `%`)...
363 364

```ruby
365
<%%= stylesheet_include_tag :application %>
366 367
```

J
Jon Atack 已提交
368
...to generate the following output:
369 370 371 372 373

```ruby
<%= stylesheet_include_tag :application %>
```

374 375
Adding Generators Fallbacks
---------------------------
P
Pratik Naik 已提交
376

377
One last feature about generators which is quite useful for plugin generators is fallbacks. For example, imagine that you want to add a feature on top of TestUnit like [shoulda](https://github.com/thoughtbot/shoulda) does. Since TestUnit already implements all generators required by Rails and shoulda just wants to overwrite part of it, there is no need for shoulda to reimplement some generators again, it can simply tell Rails to use a `TestUnit` generator if none was found under the `Shoulda` namespace.
P
Pratik Naik 已提交
378

379
We can easily simulate this behavior by changing our `config/application.rb` once again:
P
Pratik Naik 已提交
380

381
```ruby
P
Pratik Naik 已提交
382 383 384
config.generators do |g|
  g.orm             :active_record
  g.template_engine :erb
385
  g.test_framework  :shoulda, fixture: false
P
Pratik Naik 已提交
386 387
  g.stylesheets     false

388
  # Add a fallback!
389
  g.fallbacks[:shoulda] = :test_unit
390
end
391
```
P
Pratik Naik 已提交
392

X
Xavier Noria 已提交
393
Now, if you create a Comment scaffold, you will see that the shoulda generators are being invoked, and at the end, they are just falling back to TestUnit generators:
P
Pratik Naik 已提交
394

P
Prem Sichanugrist 已提交
395
```bash
396
$ bin/rails generate scaffold Comment body:text
P
Pratik Naik 已提交
397
      invoke  active_record
398
      create    db/migrate/20130924143118_create_comments.rb
P
Pratik Naik 已提交
399 400
      create    app/models/comment.rb
      invoke    shoulda
M
Mike Moore 已提交
401
      create      test/models/comment_test.rb
P
Pratik Naik 已提交
402
      create      test/fixtures/comments.yml
403
      invoke  resource_route
404
       route    resources :comments
P
Pratik Naik 已提交
405 406 407 408 409 410 411 412 413 414
      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
      invoke    shoulda
M
Mike Moore 已提交
415
      create      test/controllers/comments_controller_test.rb
P
Pratik Naik 已提交
416 417
      invoke    my_helper
      create      app/helpers/comments_helper.rb
418 419 420
      invoke    jbuilder
      create      app/views/comments/index.json.jbuilder
      create      app/views/comments/show.json.jbuilder
421 422 423
      invoke  test_unit
      create    test/application_system_test_case.rb
      create    test/system/comments_test.rb
424 425
      invoke  assets
      invoke    scss
426
      create    app/assets/stylesheets/scaffolds.scss
427
```
P
Pratik Naik 已提交
428

429
Fallbacks allow your generators to have a single responsibility, increasing code reuse and reducing the amount of duplication.
P
Pratik Naik 已提交
430

431 432
Application Templates
---------------------
433

E
Eric Henziger 已提交
434
Now that you've seen how generators can be used _inside_ an application, did you know they can also be used to _generate_ applications too? This kind of generator is referred to as a "template". This is a brief overview of the Templates API. For detailed documentation see the [Rails Application Templates guide](rails_application_templates.html).
435

436
```ruby
437 438
gem "rspec-rails", group: "test"
gem "cucumber-rails", group: "test"
V
Vijay Dev 已提交
439 440

if yes?("Would you like to install Devise?")
441 442
  gem "devise"
  generate "devise:install"
V
Vijay Dev 已提交
443 444
  model_name = ask("What would you like the user model to be called? [user]")
  model_name = "user" if model_name.blank?
445
  generate "devise", model_name
V
Vijay Dev 已提交
446
end
447
```
448

449
In the above template we specify that the application relies on the `rspec-rails` and `cucumber-rails` gem so these two will be added to the `test` group in the `Gemfile`. Then we pose a question to the user about whether or not they would like to install Devise. If the user replies "y" or "yes" to this question, then the template will add Devise to the `Gemfile` outside of any group and then runs the `devise:install` generator. This template then takes the users input and runs the `devise` generator, with the user's answer from the last question being passed to this generator.
450

451
Imagine that this template was in a file called `template.rb`. We can use it to modify the outcome of the `rails new` command by using the `-m` option and passing in the filename:
452

P
Prem Sichanugrist 已提交
453
```bash
454
$ rails new thud -m template.rb
455
```
456

457
This command will generate the `Thud` application, and then apply the template to the generated output.
458

459
Templates don't have to be stored on the local system, the `-m` option also supports online templates:
460

P
Prem Sichanugrist 已提交
461
```bash
A
Akira Matsuda 已提交
462
$ rails new thud -m https://gist.github.com/radar/722911/raw/
463
```
464

465 466
Whilst the final section of this guide doesn't cover how to generate the most awesome template known to man, it will take you through the methods available at your disposal so that you can develop it yourself. These same methods are also available for generators.

467 468
Adding Command Line Arguments
-----------------------------
J
Juanjo Bazán 已提交
469
Rails generators can be easily modified to accept custom command line arguments. This functionality comes from [Thor](https://www.rubydoc.info/github/erikhuda/thor/master/Thor/Base/ClassMethods#class_option-instance_method):
470

471
```ruby
472 473 474 475 476 477
class_option :scope, type: :string, default: 'read_products'
```

Now our generator can be invoked as follows:

```bash
478
$ bin/rails generate initializer --scope write_products
479 480 481 482 483 484 485 486
```

The command line arguments are accessed through the `options` method inside the generator class. e.g:

```ruby
@scope = options['scope']
```

487 488
Generator methods
-----------------
489

V
Vijay Dev 已提交
490
The following are methods available for both generators and templates for Rails.
491

J
Juanjo Bazán 已提交
492
NOTE: Methods provided by Thor are not covered this guide and can be found in [Thor's documentation](https://rdoc.info/github/erikhuda/thor/master/Thor/Actions.html)
493

494
### `gem`
495 496 497

Specifies a gem dependency of the application.

498
```ruby
499 500
gem "rspec", group: "test", version: "2.1.0"
gem "devise", "1.1.5"
501
```
502 503 504

Available options are:

505 506 507
* `:group` - The group in the `Gemfile` where this gem should go.
* `:version` - The version string of the gem you want to use. Can also be specified as the second argument to the method.
* `:git` - The URL to the git repository for this gem.
508 509 510

Any additional options passed to this method are put on the end of the line:

511
```ruby
512
gem "devise", git: "https://github.com/plataformatec/devise.git", branch: "master"
513
```
514

515
The above code will put the following line into `Gemfile`:
516

517
```ruby
518
gem "devise", git: "https://github.com/plataformatec/devise.git", branch: "master"
519
```
520

521
### `gem_group`
522 523 524

Wraps gem entries inside a group:

525
```ruby
526 527 528
gem_group :development, :test do
  gem "rspec-rails"
end
529
```
530

531
### `add_source`
532

533
Adds a specified source to `Gemfile`:
534

535
```ruby
V
Vijay Dev 已提交
536
add_source "http://gems.github.com"
537
```
538

539 540 541 542 543 544 545 546
This method also takes a block:

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

547
### `inject_into_file`
548 549 550

Injects a block of code into a defined position in your file.

551
```ruby
552
inject_into_file 'name_of_file.rb', after: "#The code goes below this line. Don't forget the Line break at the end\n" do <<-'RUBY'
553 554 555
  puts "Hello World"
RUBY
end
556
```
557

558
### `gsub_file`
559 560 561

Replaces text inside a file.

562
```ruby
V
Vijay Dev 已提交
563
gsub_file 'name_of_file.rb', 'method.to_be_replaced', 'method.the_replacing_code'
564
```
565

566
Regular Expressions can be used to make this method more precise. You can also use `append_file` and `prepend_file` in the same way to place code at the beginning and end of a file respectively.
567

568
### `application`
569

570
Adds a line to `config/application.rb` directly after the application class definition.
571

572
```ruby
V
Vijay Dev 已提交
573
application "config.asset_host = 'http://example.com'"
574
```
575 576 577

This method can also take a block:

578
```ruby
V
Vijay Dev 已提交
579 580 581
application do
  "config.asset_host = 'http://example.com'"
end
582
```
583 584 585

Available options are:

586
* `:env` - Specify an environment for this configuration option. If you wish to use this option with the block syntax the recommended syntax is as follows:
587

588
```ruby
589
application(nil, env: "development") do
V
Vijay Dev 已提交
590 591
  "config.asset_host = 'http://localhost:3000'"
end
592
```
593

594
### `git`
595 596 597

Runs the specified git command:

598
```ruby
V
Vijay Dev 已提交
599
git :init
600 601 602
git add: "."
git commit: "-m First commit!"
git add: "onefile.rb", rm: "badfile.cxx"
603
```
604 605 606

The values of the hash here being the arguments or options passed to the specific git command. As per the final example shown here, multiple git commands can be specified at a time, but the order of their running is not guaranteed to be the same as the order that they were specified in.

607
### `vendor`
608

609
Places a file into `vendor` which contains the specified code.
610

611
```ruby
612
vendor "sekrit.rb", '#top secret stuff'
613
```
614 615 616

This method also takes a block:

617
```ruby
618
vendor "seeds.rb" do
619
  "puts 'in your app, seeding your database'"
V
Vijay Dev 已提交
620
end
621
```
622

623
### `lib`
624

625
Places a file into `lib` which contains the specified code.
626

627
```ruby
628
lib "special.rb", "p Rails.root"
629
```
630 631 632

This method also takes a block:

633
```ruby
634
lib "super_special.rb" do
635
  "puts 'Super special!'"
V
Vijay Dev 已提交
636
end
637
```
638

639
### `rakefile`
640

641
Creates a Rake file in the `lib/tasks` directory of the application.
642

643
```ruby
644
rakefile "test.rake", 'task(:hello) { puts "Hello, there" }'
645
```
646 647 648

This method also takes a block:

649
```ruby
650
rakefile "test.rake" do
V
Vijay Dev 已提交
651
  %Q{
652
    task rock: :environment do
V
Vijay Dev 已提交
653 654 655 656
      puts "Rockin'"
    end
  }
end
657
```
658

659
### `initializer`
660

661
Creates an initializer in the `config/initializers` directory of the application:
662

663
```ruby
664
initializer "begin.rb", "puts 'this is the beginning'"
665
```
666

667
This method also takes a block, expected to return a string:
668

669
```ruby
670
initializer "begin.rb" do
671
  "puts 'this is the beginning'"
V
Vijay Dev 已提交
672
end
673
```
674

675
### `generate`
676 677 678

Runs the specified generator where the first argument is the generator name and the remaining arguments are passed directly to the generator.

679
```ruby
680
generate "scaffold", "forums title:string description:text"
681
```
682 683


684
### `rake`
685 686 687

Runs the specified Rake task.

688
```ruby
689
rake "db:migrate"
690
```
691 692 693

Available options are:

694 695
* `:env` - Specifies the environment in which to run this rake task.
* `:sudo` - Whether or not to run this task using `sudo`. Defaults to `false`.
696

697
### `route`
698

699
Adds text to the `config/routes.rb` file:
700

701
```ruby
702
route "resources :people"
703
```
704

705
### `readme`
706

707
Output the contents of a file in the template's `source_path`, usually a README.
708

709
```ruby
710
readme "README"
711
```