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

S
Steve Klabnik 已提交
3 4
The Rails Command Line
======================
5

6 7
After reading this guide, you will know:

8 9 10 11
* How to create a Rails application.
* How to generate models, controllers, database migrations, and unit tests.
* How to start a development server.
* How to experiment with objects through an interactive shell.
12

13
--------------------------------------------------------------------------------
14

15
NOTE: This tutorial assumes you have basic Rails knowledge from reading the [Getting Started with Rails Guide](getting_started.html).
16

17 18
Command Line Basics
-------------------
19 20 21

There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:

22 23
* `rails console`
* `rails server`
24
* `rails test`
25
* `rails generate`
26 27 28
* `rails db:migrate`
* `rails db:create`
* `rails routes`
29 30
* `rails dbconsole`
* `rails new app_name`
31

32 33 34 35 36 37 38
You can get a list of rails commands available to you, which will often depend on your current directory, by typing `rails --help`. Each command has a description, and should help you find the thing you need.

```bash
$ rails --help
Usage: rails COMMAND [ARGS]

The most common rails commands are:
39 40 41 42
 generate    Generate new code (short-cut alias: "g")
 console     Start the Rails console (short-cut alias: "c")
 server      Start the Rails server (short-cut alias: "s")
 ...
43 44 45 46

All commands can be run with -h (or --help) for more information.

In addition to those commands, there are:
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
 about                               List versions of all Rails ...
 assets:clean[keep]                  Remove old compiled assets
 assets:clobber                      Remove compiled assets
 assets:environment                  Load asset compile environment
 assets:precompile                   Compile all the assets ...
 ...
 db:fixtures:load                    Loads fixtures into the ...
 db:migrate                          Migrate the database ...
 db:migrate:status                   Display status of migrations
 db:rollback                         Rolls the schema back to ...
 db:schema:cache:clear               Clears a db/schema_cache.yml file
 db:schema:cache:dump                Creates a db/schema_cache.yml file
 db:schema:dump                      Creates a db/schema.rb file ...
 db:schema:load                      Loads a schema.rb file ...
 db:seed                             Loads the seed data ...
 db:structure:dump                   Dumps the database structure ...
 db:structure:load                   Recreates the databases ...
 db:version                          Retrieves the current schema ...
 ...
 restart                             Restart app by touching ...
 tmp:create                          Creates tmp directories ...
68
```
V
Vishnu Atrai 已提交
69

70 71
Let's create a simple Rails application to step through each of these commands in context.

72
### `rails new`
73

74
The first thing we'll want to do is create a new Rails application by running the `rails new` command after installing Rails.
75

76
INFO: You can install the rails gem by typing `gem install rails`, if you don't have it already.
77

P
Prem Sichanugrist 已提交
78
```bash
79
$ rails new commandsapp
80
     create
81
     create  README.md
M
Mikel Lindsaar 已提交
82 83
     create  Rakefile
     create  config.ru
84
     create  .gitignore
M
Mikel Lindsaar 已提交
85 86
     create  Gemfile
     create  app
87
     ...
M
Mikel Lindsaar 已提交
88
     create  tmp/cache
89 90
     ...
        run  bundle install
91
```
92 93 94

Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.

95
### `rails server`
96

97
The `rails server` command launches a web server named Puma which comes bundled with Rails. You'll use this any time you want to access your application through a web browser.
98

99
With no further work, `rails server` will run our new shiny Rails app:
100

P
Prem Sichanugrist 已提交
101
```bash
102
$ cd commandsapp
103
$ rails server
104
=> Booting Puma
105 106
=> Rails 6.0.0 application starting in development
=> Run `rails server --help` for more startup options
107
Puma starting in single mode...
108
* Version 3.12.1 (ruby 2.5.7-p206), codename: Llamas in Pajamas
109
* Min threads: 5, max threads: 5
110 111
* Environment: development
* Listening on tcp://localhost:3000
112
Use Ctrl-C to stop
113
```
114

115
With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open [http://localhost:3000](http://localhost:3000), you will see a basic Rails app running.
116

117
INFO: You can also use the alias "s" to start the server: `rails s`.
118

119
The server can be run on a different port using the `-p` option. The default development environment can be changed using `-e`.
V
Vijay Dev 已提交
120

P
Prem Sichanugrist 已提交
121
```bash
122
$ rails server -e production -p 4000
123
```
V
Vijay Dev 已提交
124

125
The `-b` option binds Rails to the specified IP, by default it is localhost. You can run a server as a daemon by passing a `-d` option.
126

127
### `rails generate`
128

129
The `rails generate` command uses templates to create a whole lot of things. Running `rails generate` by itself gives a list of available generators:
130

131
INFO: You can also use the alias "g" to invoke the generator command: `rails g`.
132

P
Prem Sichanugrist 已提交
133
```bash
134
$ rails generate
V
Vijay Dev 已提交
135
Usage: rails generate GENERATOR [args] [options]
136 137 138 139

...
...

M
Mikel Lindsaar 已提交
140
Please choose a generator below.
141

M
Mikel Lindsaar 已提交
142
Rails:
143
  assets
144
  channel
M
Mikel Lindsaar 已提交
145 146 147 148
  controller
  generator
  ...
  ...
149
```
150 151 152

NOTE: You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!

153
Using generators will save you a large amount of time by writing **boilerplate code**, code that is necessary for the app to work.
154 155 156

Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:

157
INFO: All Rails console utilities have help text. As with most *nix utilities, you can try adding `--help` or `-h` to the end, for example `rails server --help`.
158

P
Prem Sichanugrist 已提交
159
```bash
160
$ rails generate controller
V
Vijay Dev 已提交
161
Usage: rails generate controller NAME [action action] [options]
162 163 164 165

...
...

166 167 168
Description:
    ...

169
    To create a controller within a module, specify the controller name as a path like 'parent_module/controller_name'.
170 171 172

    ...

173
Example:
174
    `rails generate controller CreditCards open debit credit close`
175

176
    Credit card controller with URLs like /credit_cards/debit.
177
        Controller: app/controllers/credit_cards_controller.rb
178 179 180
        Test:       test/controllers/credit_cards_controller_test.rb
        Views:      app/views/credit_cards/debit.html.erb [...]
        Helper:     app/helpers/credit_cards_helper.rb
181
```
182

183
The controller generator is expecting parameters in the form of `generate controller ControllerName action1 action2`. Let's make a `Greetings` controller with an action of **hello**, which will say something nice to us.
184

P
Prem Sichanugrist 已提交
185
```bash
186
$ rails generate controller Greetings hello
187
     create  app/controllers/greetings_controller.rb
188
      route  get 'greetings/hello'
M
Mikel Lindsaar 已提交
189 190 191
     invoke  erb
     create    app/views/greetings
     create    app/views/greetings/hello.html.erb
V
Vijay Dev 已提交
192
     invoke  test_unit
M
Mike Moore 已提交
193
     create    test/controllers/greetings_controller_test.rb
M
Mikel Lindsaar 已提交
194 195
     invoke  helper
     create    app/helpers/greetings_helper.rb
196
     invoke    test_unit
197
     invoke  assets
198
     invoke    scss
199
     create      app/assets/stylesheets/greetings.scss
200
```
201

A
Anthony Crumley 已提交
202
What all did this generate? It made sure a bunch of directories were in our application, and created a controller file, a view file, a functional test file, a helper for the view, a JavaScript file, and a stylesheet file.
203

204
Check out the controller and modify it a little (in `app/controllers/greetings_controller.rb`):
205

206
```ruby
P
Pratik Naik 已提交
207
class GreetingsController < ApplicationController
208
  def hello
M
Mikel Lindsaar 已提交
209
    @message = "Hello, how are you today?"
210 211
  end
end
212
```
213

214
Then the view, to display our message (in `app/views/greetings/hello.html.erb`):
215

216
```erb
217 218
<h1>A Greeting for You!</h1>
<p><%= @message %></p>
219
```
220

221
Fire up your server using `rails server`.
222

P
Prem Sichanugrist 已提交
223
```bash
224
$ rails server
225
=> Booting Puma...
226
```
227

228
The URL will be [http://localhost:3000/greetings/hello](http://localhost:3000/greetings/hello).
229

230
INFO: With a normal, plain-old Rails application, your URLs will generally follow the pattern of http://(host)/(controller)/(action), and a URL like http://(host)/(controller) will hit the **index** action of that controller.
231

V
Vijay Dev 已提交
232
Rails comes with a generator for data models too.
233

P
Prem Sichanugrist 已提交
234
```bash
235
$ rails generate model
236 237
Usage:
  rails generate model NAME [field[:type][:index] field[:type][:index]] [options]
238 239 240

...

Y
Yves Senn 已提交
241
Active Record options:
242 243
      [--migration]            # Indicates when to generate migration
                               # Default: true
244

245
...
246

247 248
Description:
    Create rails files for model generator.
249
```
250

251
NOTE: For a list of available field types for the `type` parameter, refer to the [API documentation](https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column) for the add_column method for the `SchemaStatements` module. The `index` parameter generates a corresponding index for the column.
252

253
But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A **scaffold** in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.
254

M
Mikel Lindsaar 已提交
255
We will set up a simple resource called "HighScore" that will keep track of our highest score on video games we play.
256

P
Prem Sichanugrist 已提交
257
```bash
258
$ rails generate scaffold HighScore game:string score:integer
259
    invoke  active_record
260
    create    db/migrate/20190416145729_create_high_scores.rb
261
    create    app/models/high_score.rb
262
    invoke    test_unit
M
Mike Moore 已提交
263
    create      test/models/high_score_test.rb
264
    create      test/fixtures/high_scores.yml
265 266
    invoke  resource_route
     route    resources :high_scores
267 268 269 270 271 272 273 274 275 276
    invoke  scaffold_controller
    create    app/controllers/high_scores_controller.rb
    invoke    erb
    create      app/views/high_scores
    create      app/views/high_scores/index.html.erb
    create      app/views/high_scores/edit.html.erb
    create      app/views/high_scores/show.html.erb
    create      app/views/high_scores/new.html.erb
    create      app/views/high_scores/_form.html.erb
    invoke    test_unit
M
Mike Moore 已提交
277
    create      test/controllers/high_scores_controller_test.rb
278
    create      test/system/high_scores_test.rb
279 280
    invoke    helper
    create      app/helpers/high_scores_helper.rb
281
    invoke      test_unit
282 283 284
    invoke    jbuilder
    create      app/views/high_scores/index.json.jbuilder
    create      app/views/high_scores/show.json.jbuilder
285
    create      app/views/high_scores/_high_score.json.jbuilder
286 287
    invoke  assets
    invoke    scss
288
    create      app/assets/stylesheets/high_scores.scss
289
    invoke  scss
290
    create    app/assets/stylesheets/scaffolds.scss
291
```
292

293
The generator checks that there exist the directories for models, controllers, helpers, layouts, functional and unit tests, stylesheets, creates the views, controller, model and database migration for HighScore (creating the `high_scores` table and fields), takes care of the route for the **resource**, and new tests for everything.
294

295
The migration requires that we **migrate**, that is, run some Ruby code (living in that `20130717151933_create_high_scores.rb`) to modify the schema of our database. Which database? The SQLite3 database that Rails will create for you when we run the `rails db:migrate` command. We'll talk more about that command below.
296

P
Prem Sichanugrist 已提交
297
```bash
298
$ rails db:migrate
M
Mikel Lindsaar 已提交
299 300
==  CreateHighScores: migrating ===============================================
-- create_table(:high_scores)
301 302
   -> 0.0017s
==  CreateHighScores: migrated (0.0019s) ======================================
303
```
304

305 306 307 308 309
INFO: Let's talk about unit tests. Unit tests are code that tests and makes assertions
about code. In unit testing, we take a little part of code, say a method of a model,
and test its inputs and outputs. Unit tests are your friend. The sooner you make
peace with the fact that your quality of life will drastically increase when you unit
test your code, the better. Seriously. Please visit
310
[the testing guide](https://guides.rubyonrails.org/testing.html) for an in-depth
311
look at unit testing.
312

313
Let's see the interface Rails created for us.
314

P
Prem Sichanugrist 已提交
315
```bash
316
$ rails server
317
```
318

319
Go to your browser and open [http://localhost:3000/high_scores](http://localhost:3000/high_scores), now we can create new high scores (55,160 on Space Invaders!)
320

321
### `rails console`
322

323
The `console` command lets you interact with your Rails application from the command line. On the underside, `rails console` uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.
324

325
INFO: You can also use the alias "c" to invoke the console: `rails c`.
326

327
You can specify the environment in which the `console` command should operate.
328

P
Prem Sichanugrist 已提交
329
```bash
330
$ rails console -e staging
331
```
332

333
If you wish to test out some code without changing any data, you can do that by invoking `rails console --sandbox`.
334

P
Prem Sichanugrist 已提交
335
```bash
336
$ rails console --sandbox
337
Loading development environment in sandbox (Rails 5.1.0)
338 339
Any modifications you make will be rolled back on exit
irb(main):001:0>
340
```
341

342 343 344 345
#### The app and helper objects

Inside the `rails console` you have access to the `app` and `helper` instances.

346
With the `app` method you can access named route helpers, as well as do requests.
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

```bash
>> app.root_path
=> "/"

>> app.get _
Started GET "/" for 127.0.0.1 at 2014-06-19 10:41:57 -0300
...
```

With the `helper` method it is possible to access Rails and your application's helpers.

```bash
>> helper.time_ago_in_words 30.days.ago
=> "about 1 month"

>> helper.my_custom_helper
=> "my custom helper"
```

367
### `rails dbconsole`
368

A
Anthony Crumley 已提交
369
`rails dbconsole` figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL (including MariaDB), PostgreSQL, and SQLite3.
370

371
INFO: You can also use the alias "db" to invoke the dbconsole: `rails db`.
372

373
### `rails runner`
374

375
`runner` runs Ruby code in the context of Rails non-interactively. For instance:
376

P
Prem Sichanugrist 已提交
377
```bash
378
$ rails runner "Model.long_running_method"
379
```
380

381
INFO: You can also use the alias "r" to invoke the runner: `rails r`.
382

383
You can specify the environment in which the `runner` command should operate using the `-e` switch.
384

P
Prem Sichanugrist 已提交
385
```bash
386
$ rails runner -e staging "Model.long_running_method"
387
```
388

389 390 391
You can even execute ruby code written in a file with runner.

```bash
392
$ rails runner lib/code_to_be_run.rb
393 394
```

395
### `rails destroy`
396

397
Think of `destroy` as the opposite of `generate`. It'll figure out what generate did, and undo it.
398

399
INFO: You can also use the alias "d" to invoke the destroy command: `rails d`.
A
Andrey Ognevsky 已提交
400

P
Prem Sichanugrist 已提交
401
```bash
402
$ rails generate model Oops
403 404 405 406
      invoke  active_record
      create    db/migrate/20120528062523_create_oops.rb
      create    app/models/oops.rb
      invoke    test_unit
M
Mike Moore 已提交
407
      create      test/models/oops_test.rb
408
      create      test/fixtures/oops.yml
409
```
P
Prem Sichanugrist 已提交
410
```bash
411
$ rails destroy model Oops
412 413 414 415
      invoke  active_record
      remove    db/migrate/20120528062523_create_oops.rb
      remove    app/models/oops.rb
      invoke    test_unit
M
Mike Moore 已提交
416
      remove      test/models/oops_test.rb
417
      remove      test/fixtures/oops.yml
418
```
419

420
### `rails about`
421

422
`rails about` gives information about version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version. It is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.
423

P
Prem Sichanugrist 已提交
424
```bash
425
$ rails about
426
About your application's environment
J
Jeremy Daer 已提交
427
Rails version             6.0.0
J
Jeremy Daer 已提交
428
Ruby version              2.5.0 (x86_64-linux)
J
Jeremy Daer 已提交
429 430
RubyGems version          2.7.3
Rack version              2.0.4
431
JavaScript Runtime        Node.js (V8)
J
Jon Moss 已提交
432
Middleware:               Rack::Sendfile, ActionDispatch::Static, ActionDispatch::Executor, ActiveSupport::Cache::Strategy::LocalCache::Middleware, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, ActionDispatch::RemoteIp, Sprockets::Rails::QuietAssets, Rails::Rack::Logger, ActionDispatch::ShowExceptions, WebConsole::Middleware, ActionDispatch::DebugExceptions, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, Rack::Head, Rack::ConditionalGet, Rack::ETag
433
Application root          /home/foobar/commandsapp
434
Environment               development
435
Database adapter          sqlite3
J
Jeremy Daer 已提交
436
Database schema version   20180205173523
437
```
438

439
### `rails assets:`
440

441
You can precompile the assets in `app/assets` using `rails assets:precompile`, and remove older compiled assets using `rails assets:clean`. The `assets:clean` command allows for rolling deploys that may still be linking to an old asset while the new assets are being built.
442

443
If you want to clear `public/assets` completely, you can use `rails assets:clobber`.
444

445
### `rails db:`
446

447
The most common commands of the `db:` rails namespace are `migrate` and `create`, and it will pay off to try out all of the migration rails commands (`up`, `down`, `redo`, `reset`). `rails db:version` is useful when troubleshooting, telling you the current version of the database.
448

Y
yui-knk 已提交
449
More information about migrations can be found in the [Migrations](active_record_migrations.html) guide.
450

451
### `rails notes`
452

453
`rails notes` searches through your code for comments beginning with a specific keyword. You can refer to `rails notes --help` for information about usage.
454 455

By default, it will search in `app`, `config`, `db`, `lib`, and `test` directories for FIXME, OPTIMIZE, and TODO annotations in files with extension `.builder`, `.rb`, `.rake`, `.yml`, `.yaml`, `.ruby`, `.css`, `.js`, and `.erb`.
V
Vijay Dev 已提交
456

P
Prem Sichanugrist 已提交
457
```bash
458
$ rails notes
V
Vijay Dev 已提交
459 460 461 462
app/controllers/admin/users_controller.rb:
  * [ 20] [TODO] any other way to do this?
  * [132] [FIXME] high priority for next deploy

463
lib/school.rb:
V
Vijay Dev 已提交
464 465
  * [ 13] [OPTIMIZE] refactor this code to make it faster
  * [ 17] [FIXME]
466
```
V
Vijay Dev 已提交
467

468
#### Annotations
R
robertomiranda 已提交
469

470 471
You can pass specific annotations by using the `--annotations` argument. By default, it will search for FIXME, OPTIMIZE, and TODO.
Note that annotations are case sensitive.
472

P
Prem Sichanugrist 已提交
473
```bash
474
$ rails notes --annotations FIXME RELEASE
475
app/controllers/admin/users_controller.rb:
476 477
  * [101] [RELEASE] We need to look at this before next release
  * [132] [FIXME] high priority for next deploy
478

479 480
lib/school.rb:
  * [ 17] [FIXME]
481
```
482

Y
Younes SERRAJ 已提交
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
#### Tags

You can add more default tags to search for by using `config.annotations.register_tags`. It receives a list of tags.

```ruby
config.annotations.register_tags("DEPRECATEME", "TESTME")
```

```bash
$ rails notes
app/controllers/admin/users_controller.rb:
  * [ 20] [TODO] do A/B testing on this
  * [ 42] [TESTME] this needs more functional tests
  * [132] [DEPRECATEME] ensure this method is deprecated in next release
```

499 500 501 502 503 504 505
#### Directories

You can add more default directories to search from by using `config.annotations.register_directories`. It receives a list of directory names.

```ruby
config.annotations.register_directories("spec", "vendor")
```
V
Vijay Dev 已提交
506

P
Prem Sichanugrist 已提交
507
```bash
508
$ rails notes
509 510 511 512 513 514 515 516 517 518 519 520 521
app/controllers/admin/users_controller.rb:
  * [ 20] [TODO] any other way to do this?
  * [132] [FIXME] high priority for next deploy

lib/school.rb:
  * [ 13] [OPTIMIZE] Refactor this code to make it faster
  * [ 17] [FIXME]

spec/models/user_spec.rb:
  * [122] [TODO] Verify the user that has a subscription works

vendor/tools.rb:
  * [ 56] [TODO] Get rid of this dependency
522
```
523

524
#### Extensions
525

526
You can add more default file extensions to search from by using `config.annotations.register_extensions`. It receives a list of extensions with its corresponding regex to match it up.
527 528

```ruby
529
config.annotations.register_extensions("scss", "sass") { |annotation| /\/\/\s*(#{annotation}):?\s*(.*)$/ }
530 531
```

P
Prem Sichanugrist 已提交
532
```bash
533
$ rails notes
534 535 536 537 538 539 540 541 542 543 544 545 546 547
app/controllers/admin/users_controller.rb:
  * [ 20] [TODO] any other way to do this?
  * [132] [FIXME] high priority for next deploy

app/assets/stylesheets/application.css.sass:
  * [ 34] [TODO] Use pseudo element for this class

app/assets/stylesheets/application.css.scss:
  * [  1] [TODO] Split into multiple components

lib/school.rb:
  * [ 13] [OPTIMIZE] Refactor this code to make it faster
  * [ 17] [FIXME]

548
spec/models/user_spec.rb:
549
  * [122] [TODO] Verify the user that has a subscription works
550 551 552

vendor/tools.rb:
  * [ 56] [TODO] Get rid of this dependency
553
```
554

555
### `rails routes`
556

557
`rails routes` will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.
558

559
### `rails test`
560

561
INFO: A good description of unit testing in Rails is given in [A Guide to Testing Rails Applications](testing.html)
562

X
Xavier Noria 已提交
563
Rails comes with a test framework called minitest. Rails owes its stability to the use of tests. The commands available in the `test:` namespace helps in running the different tests you will hopefully write.
564

565
### `rails tmp:`
566

567
The `Rails.root/tmp` directory is, like the *nix /tmp directory, the holding place for temporary files like process id files and cached actions.
568

569
The `tmp:` namespaced commands will help you clear and create the `Rails.root/tmp` directory:
570

571 572
* `rails tmp:cache:clear` clears `tmp/cache`.
* `rails tmp:sockets:clear` clears `tmp/sockets`.
573
* `rails tmp:screenshots:clear` clears `tmp/screenshots`.
A
Anthony Crumley 已提交
574 575
* `rails tmp:clear` clears all cache, sockets, and screenshot files.
* `rails tmp:create` creates tmp directories for cache, sockets, and pids.
576

577
### Miscellaneous
578

579 580 581
* `rails stats` is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio.
* `rails secret` will give you a pseudo-random key to use for your session secret.
* `rails time:zones:all` lists all the timezones Rails knows about.
582

V
Vijay Dev 已提交
583
### Custom Rake Tasks
584

585
Custom rake tasks have a `.rake` extension and are placed in
586
`Rails.root/lib/tasks`. You can create these custom rake tasks with the
587
`rails generate task` command.
588

589
```ruby
590
desc "I am short, but comprehensive description for my cool task"
A
Agis Anastasopoulos 已提交
591
task task_name: [:prerequisite_task, :another_task_we_depend_on] do
P
Przemek Hocke 已提交
592
  # All your magic here
593 594
  # Any valid Ruby code is allowed
end
595
```
596

V
Vijay Dev 已提交
597
To pass arguments to your custom rake task:
598

599
```ruby
600 601
task :task_name, [:arg_1] => [:prerequisite_1, :prerequisite_2] do |task, args|
  argument_1 = args.arg_1
602
end
603
```
604 605 606

You can group tasks by placing them in namespaces:

607
```ruby
608
namespace :db do
609 610 611 612 613
  desc "This task does nothing"
  task :nothing do
    # Seriously, nothing
  end
end
614
```
615

V
Vijay Dev 已提交
616
Invocation of the tasks will look like:
617

P
Prem Sichanugrist 已提交
618
```bash
619 620 621
$ rails task_name
$ rails "task_name[value 1]" # entire argument string should be quoted
$ rails db:nothing
622
```
623

S
Sergio 已提交
624
NOTE: If you need to interact with your application models, perform database queries, and so on, your task should depend on the `environment` task, which will load your application code.
625

626 627
The Rails Advanced Command Line
-------------------------------
628

629
More advanced use of the command line is focused around finding useful (even surprising at times) options in the utilities, and fitting those to your needs and specific work flow. Listed here are some tricks up Rails' sleeve.
630

631
### Rails with Databases and SCM
632 633 634

When creating a new Rails application, you have the option to specify what kind of database and what kind of source code management system your application is going to use. This will save you a few minutes, and certainly many keystrokes.

635
Let's see what a `--git` option and a `--database=postgresql` option will do for us:
636

P
Prem Sichanugrist 已提交
637
```bash
638 639 640 641
$ mkdir gitapp
$ cd gitapp
$ git init
Initialized empty Git repository in .git/
642
$ rails new . --git --database=postgresql
643 644 645 646 647 648 649 650 651
      exists
      create  app/controllers
      create  app/helpers
...
...
      create  tmp/cache
      create  tmp/pids
      create  Rakefile
add 'Rakefile'
652 653
      create  README.md
add 'README.md'
V
Vijay Dev 已提交
654 655
      create  app/controllers/application_controller.rb
add 'app/controllers/application_controller.rb'
656 657 658 659
      create  app/helpers/application_helper.rb
...
      create  log/test.log
add 'log/test.log'
660
```
661

662
We had to create the **gitapp** directory and initialize an empty git repository before Rails would add files it created to our repository. Let's see what it put in our database configuration:
663

P
Prem Sichanugrist 已提交
664
```bash
665
$ cat config/database.yml
666
# PostgreSQL. Versions 9.1 and up are supported.
667
#
668 669
# Install the pg driver:
#   gem install pg
X
Xavier Noria 已提交
670
# On macOS with Homebrew:
671
#   gem install pg -- --with-pg-config=/usr/local/bin/pg_config
X
Xavier Noria 已提交
672
# On macOS with MacPorts:
673
#   gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config
674
# On Windows:
675
#   gem install pg
676 677
#       Choose the win32 build.
#       Install PostgreSQL and put its /bin directory on your path.
678 679 680 681
#
# Configure Using Gemfile
# gem 'pg'
#
682
default: &default
683 684
  adapter: postgresql
  encoding: unicode
685
  # For details on connection pooling, see Rails configuration guide
686
  # https://guides.rubyonrails.org/configuring.html#database-pooling
687 688 689 690
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
691 692 693
  database: gitapp_development
...
...
694
```
695

Y
Yauheni Dakuka 已提交
696
It also generated some lines in our `database.yml` configuration corresponding to our choice of PostgreSQL for database.
697

698
NOTE. The only catch with using the SCM options is that you have to make your application's directory first, then initialize your SCM, then you can run the `rails new` command to generate the basis of your app.