1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
|
h2. A Guide to The Rails Command Line
Rails comes with every command line tool you'll need to
* Create a Rails application
* Generate models, controllers, database migrations, and unit tests
* Start a development server
* Mess with objects through an interactive shell
* Profile and benchmark your new creation
endprologue.
NOTE: This tutorial assumes you have basic Rails knowledge from reading the "Getting Started with Rails Guide":getting_started.html.
WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.
h3. Command Line Basics
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:
* <tt>rails console</tt>
* <tt>rails server</tt>
* <tt>rake</tt>
* <tt>rails generate</tt>
* <tt>rails dbconsole</tt>
* <tt>rails new app_name</tt>
Let's create a simple Rails application to step through each of these commands in context.
h4. +rails new+
The first thing we'll want to do is create a new Rails application by running the +rails new+ command after installing Rails.
WARNING: You can install the rails gem by typing +gem install rails+, if you don't have it already. Follow the instructions in the "Rails 3 Release Notes":/3_0_release_notes.html
<shell>
$ rails new commandsapp
create
create README
create .gitignore
create Rakefile
create config.ru
create Gemfile
create app
...
create tmp/cache
create tmp/pids
create vendor/plugins
create vendor/plugins/.gitkeep
</shell>
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.
INFO: This output will seem very familiar when we get to the +generate+ command. Creepy foreshadowing!
h4. +rails server+
The +rails server+ command launches a small web server named WEBrick which comes bundled with Ruby. You'll use this any time you want to view your work through a web browser.
INFO: WEBrick isn't your only option for serving Rails. We'll get to that in a later section.
Without any prodding of any kind, +rails server+ will run our new shiny Rails app:
<shell>
$ cd commandsapp
$ rails server
=> Booting WEBrick
=> Rails 3.1.0 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2010-04-18 03:20:33] INFO WEBrick 1.3.1
[2010-04-18 03:20:33] INFO ruby 1.8.7 (2010-01-10) [x86_64-linux]
[2010-04-18 03:20:33] INFO WEBrick::HTTPServer#start: pid=26086 port=3000
</shell>
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.
You can also use the alias "s" to start the server: <tt>rails s</tt>.
h4. +rails generate+
The +rails generate+ command uses templates to create a whole lot of things. You can always find out what's available by running +rails generate+ by itself. Let's do that:
<shell>
$ rails generate
Usage: rails generate generator [args] [options]
...
...
Please choose a generator below.
Rails:
controller
generator
...
...
</shell>
NOTE: You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!
Using generators will save you a large amount of time by writing *boilerplate code*, code that is necessary for the app to work, but not necessary for you to spend time writing. That's what we have computers for.
Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
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+.
<shell>
$ rails generate controller
Usage: rails generate controller NAME [action action] [options]
...
...
Example:
rails generate controller CreditCard open debit credit close
Credit card controller with URLs like /credit_card/debit.
Controller: app/controllers/credit_card_controller.rb
Views: app/views/credit_card/debit.html.erb [...]
Helper: app/helpers/credit_card_helper.rb
Test: test/functional/credit_card_controller_test.rb
Modules Example:
rails generate controller 'admin/credit_card' suspend late_fee
Credit card admin controller with URLs like /admin/credit_card/suspend.
Controller: app/controllers/admin/credit_card_controller.rb
Views: app/views/admin/credit_card/debit.html.erb [...]
Helper: app/helpers/admin/credit_card_helper.rb
Test: test/functional/admin/credit_card_controller_test.rb
</shell>
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.
<shell>
$ rails generate controller Greetings hello
create app/controllers/greetings_controller.rb
route get "greetings/hello"
invoke erb
create app/views/greetings
create app/views/greetings/hello.html.erb
invoke test_unit
create test/functional/greetings_controller_test.rb
invoke helper
create app/helpers/greetings_helper.rb
invoke test_unit
create test/unit/helpers/greetings_helper_test.rb
invoke assets
create app/assets/javascripts/greetings.js
create app/assets/stylesheets/greetings.css
</shell>
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.
Check out the controller and modify it a little (in +app/controllers/greetings_controller.rb+):
<ruby>
class GreetingsController < ApplicationController
def hello
@message = "Hello, how are you today?"
end
end
</ruby>
Then the view, to display our message (in +app/views/greetings/hello.html.erb+):
<html>
<h1>A Greeting for You!</h1>
<p><%= @message %></p>
</html>
Deal. Go check it out in your browser. Fire up your server using +rails server+.
<shell>
$ rails server
=> Booting WEBrick...
</shell>
WARNING: Make sure that you do not have any "tilde backup" files in +app/views/(controller)+, or else WEBrick will _not_ show the expected output. This seems to be a *bug* in Rails 2.3.0.
The URL will be "http://localhost:3000/greetings/hello":http://localhost:3000/greetings/hello.
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.
Rails comes with a generator for data models too:
<shell>
$ rails generate model
Usage: rails generate model NAME [field:type field:type] [options]
...
Examples:
rails generate model account
Model: app/models/account.rb
Test: test/unit/account_test.rb
Fixtures: test/fixtures/accounts.yml
Migration: db/migrate/XXX_add_accounts.rb
rails generate model post title:string body:text published:boolean
Creates a Post model with a string title, text body, and published flag.
</shell>
NOTE: For a list of available field types, refer to the "API documentation":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#method-i-column for the column method for the +TableDefinition+ class.
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.
We will set up a simple resource called "HighScore" that will keep track of our highest score on video games we play.
<shell>
$ rails generate scaffold HighScore game:string score:integer
exists app/models/
exists app/controllers/
exists app/helpers/
create app/views/high_scores
create app/views/layouts/
exists test/functional/
create test/unit/
create app/assets/stylesheets/
create app/views/high_scores/index.html.erb
create app/views/high_scores/show.html.erb
create app/views/high_scores/new.html.erb
create app/views/high_scores/edit.html.erb
create app/views/layouts/high_scores.html.erb
create app/assets/stylesheets/scaffold.css.scss
create app/controllers/high_scores_controller.rb
create test/functional/high_scores_controller_test.rb
create app/helpers/high_scores_helper.rb
route resources :high_scores
dependency model
exists app/models/
exists test/unit/
create test/fixtures/
create app/models/high_score.rb
create test/unit/high_score_test.rb
create test/fixtures/high_scores.yml
exists db/migrate
create db/migrate/20100209025147_create_high_scores.rb
</shell>
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.
The migration requires that we *migrate*, that is, run some Ruby code (living in that +20100209025147_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 +rake db:migrate+ command. We'll talk more about Rake in-depth in a little while.
<shell>
$ rake db:migrate
(in /home/foobar/commandsapp)
== CreateHighScores: migrating ===============================================
-- create_table(:high_scores)
-> 0.0026s
== CreateHighScores: migrated (0.0028s) ======================================
</shell>
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. We'll make one in a moment.
Let's see the interface Rails created for us.
<shell>
$ rails server
</shell>
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!)
h4. +rails console+
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.
You can also use the alias "c" to invoke the console: <tt>rails c</tt>.
If you wish to test out some code without changing any data, you can do that by invoking +rails console --sandbox+.
<shell>
$ rails console --sandbox
Loading development environment in sandbox (Rails 3.1.0)
Any modifications you make will be rolled back on exit
irb(main):001:0>
</shell>
h4. +rails dbconsole+
+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, PostgreSQL, SQLite and SQLite3.
You can also use the alias "db" to invoke the dbconsole: <tt>rails db</tt>.
h4. +rails plugin+
The +rails plugin+ command simplifies plugin management; think a miniature version of the Gem utility. Let's walk through installing a plugin. You can call the sub-command +discover+, which sifts through repositories looking for plugins, or call +source+ to add a specific repository of plugins, or you can specify the plugin location directly.
Let's say you're creating a website for a client who wants a small accounting system. Every event having to do with money must be logged, and must never be deleted. Wouldn't it be great if we could override the behavior of a model to never actually take its record out of the database, but instead, just set a field?
There is such a thing! The plugin we're installing is called +acts_as_paranoid+, and it lets models implement a +deleted_at+ column that gets set when you call destroy. Later, when calling find, the plugin will tack on a database check to filter out "deleted" things.
<shell>
$ rails plugin install https://github.com/technoweenie/acts_as_paranoid.git
+ ./CHANGELOG
+ ./MIT-LICENSE
...
...
</shell>
h4. +rails runner+
<tt>runner</tt> runs Ruby code in the context of Rails non-interactively. For instance:
<shell>
$ rails runner "Model.long_running_method"
</shell>
h4. +rails destroy+
Think of +destroy+ as the opposite of +generate+. It'll figure out what generate did, and undo it.
<shell>
$ rails generate model Oops
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/oops.rb
create test/unit/oops_test.rb
create test/fixtures/oops.yml
exists db/migrate
create db/migrate/20081221040817_create_oops.rb
$ rails destroy model Oops
notempty db/migrate
notempty db
rm db/migrate/20081221040817_create_oops.rb
rm test/fixtures/oops.yml
rm test/unit/oops_test.rb
rm app/models/oops.rb
notempty test/fixtures
notempty test
notempty test/unit
notempty test
notempty app/models
notempty app
</shell>
h4. +rake about+
Check it: 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! +about+ 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.
<shell>
$ rake about
About your application's environment
Ruby version 1.8.7 (x86_64-linux)
RubyGems version 1.3.6
Rack version 1.1
Rails version 3.1.0
Active Record version 3.1.0
Action Pack version 3.1.0
Active Resource version 3.1.0
Action Mailer version 3.1.0
Active Support version 3.1.0
Middleware ActionDispatch::Static, Rack::Lock, Rack::Runtime, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::RemoteIp, Rack::Sendfile, ActionDispatch::Callbacks, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::MethodOverride, ActionDispatch::Head
Application root /home/foobar/commandsapp
Environment development
</shell>
h3. The Rails Advanced Command Line
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.
h4. Rails with Databases and SCM
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.
Let's see what a +--git+ option and a +--database=postgresql+ option will do for us:
<shell>
$ mkdir gitapp
$ cd gitapp
$ git init
Initialized empty Git repository in .git/
$ rails new . --git --database=postgresql
exists
create app/controllers
create app/helpers
...
...
create tmp/cache
create tmp/pids
create Rakefile
add 'Rakefile'
create README
add 'README'
create app/controllers/application_controller.rb
add 'app/controllers/application_controller.rb'
create app/helpers/application_helper.rb
...
create log/test.log
add 'log/test.log'
</shell>
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:
<shell>
$ cat config/database.yml
# PostgreSQL. Versions 7.4 and 8.x are supported.
#
# Install the ruby-postgres driver:
# gem install ruby-postgres
# On Mac OS X:
# gem install ruby-postgres -- --include=/usr/local/pgsql
# On Windows:
# gem install ruby-postgres
# Choose the win32 build.
# Install PostgreSQL and put its /bin directory on your path.
development:
adapter: postgresql
encoding: unicode
database: gitapp_development
pool: 5
username: gitapp
password:
...
...
</shell>
It also generated some lines in our database.yml configuration corresponding to our choice of PostgreSQL for database. 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.
h4. +server+ with Different Backends
Many people have created a large number different web servers in Ruby, and many of them can be used to run Rails. Since version 2.3, Rails uses Rack to serve its webpages, which means that any webserver that implements a Rack handler can be used. This includes WEBrick, Mongrel, Thin, and Phusion Passenger (to name a few!).
NOTE: For more details on the Rack integration, see "Rails on Rack":rails_on_rack.html.
To use a different server, just install its gem, then use its name for the first parameter to +rails server+:
<shell>
$ sudo gem install mongrel
Building native extensions. This could take a while...
Building native extensions. This could take a while...
Successfully installed gem_plugin-0.2.3
Successfully installed fastthread-1.0.1
Successfully installed cgi_multipart_eof_fix-2.5.0
Successfully installed mongrel-1.1.5
...
...
Installing RDoc documentation for mongrel-1.1.5...
$ rails server mongrel
=> Booting Mongrel (use 'rails server webrick' to force WEBrick)
=> Rails 3.1.0 application starting on http://0.0.0.0:3000
...
</shell>
h4. The Rails Generation: Generators
INFO: For a good rundown on generators, see "Understanding Generators":http://wiki.rubyonrails.org/rails/pages/UnderstandingGenerators. A lot of its material is presented here.
Generators are code that generates code. Let's experiment by building one. Our generator will generate a text file.
The Rails generator by default looks in these places for available generators, where Rails.root is the root of your Rails application, like /home/foobar/commandsapp:
* Rails.root/lib/generators
* Rails.root/vendor/generators
* Inside any plugin with a directory like "generators" or "rails_generators"
* ~/.rails/generators
* Inside any Gem you have installed with a name ending in "_generator"
* Inside any Gem installed with a "rails_generators" path, and a file ending in "_generator.rb"
* Finally, the builtin Rails generators (controller, model, mailer, etc.)
Let's try the fourth option (in our home directory), which will be easy to clean up later:
<shell>
$ mkdir -p ~/.rails/generators/tutorial_test/templates
$ touch ~/.rails/generators/tutorial_test/templates/tutorial.erb
$ touch ~/.rails/generators/tutorial_test/tutorial_test_generator.rb
</shell>
We'll fill +tutorial_test_generator.rb+ out with:
<ruby>
class TutorialTestGenerator < Rails::Generator::Base
def initialize(*runtime_args)
super(*runtime_args)
@tut_args = runtime_args
end
def manifest
record do |m|
m.directory "public"
m.template "tutorial.erb", File.join("public", "tutorial.txt"),
:assigns => { :args => @tut_args }
end
end
end
</ruby>
We take whatever args are supplied, save them to an instance variable, and literally copying from the Rails source, implement a +manifest+ method, which calls +record+ with a block, and we:
* Check there's a *public* directory. You bet there is.
* Run the ERB template called "tutorial.erb".
* Save it into "Rails.root/public/tutorial.txt".
* Pass in the arguments we saved through the +:assigns+ parameter.
Next we'll build the template:
<shell>
$ cat ~/.rails/generators/tutorial_test/templates/tutorial.erb
I'm a template!
I got assigned some args:
<%= require 'pp'; PP.pp(args, "") %>
</shell>
Then we'll make sure it got included in the list of available generators:
<shell>
$ rails generate
...
...
Installed Generators
User: tutorial_test
</shell>
SWEET! Now let's generate some text, yeah!
<shell>
$ rails generate tutorial_test arg1 arg2 arg3
exists public
create public/tutorial.txt
</shell>
And the result:
<shell>
$ cat public/tutorial.txt
I'm a template!
I got assigned some args:
[["arg1", "arg2", "arg3"],
{:collision=>:ask,
:quiet=>false,
:generator=>"tutorial_test",
:command=>:create}]
</shell>
Tada!
h4. Rake is Ruby Make
Rake is a standalone Ruby utility that replaces the Unix utility 'make', and uses a 'Rakefile' and +.rake+ files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other.
You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing +rake --tasks+. Each task has a description, and should help you find the thing you need.
<shell>
$ rake --tasks
(in /home/foobar/commandsapp)
rake db:abort_if_pending_migrations # Raises an error if there are pending migrations
rake db:charset # Retrieves the charset for the current environment's database
rake db:collation # Retrieves the collation for the current environment's database
rake db:create # Create the database defined in config/database.yml for the current Rails.env
...
...
rake tmp:pids:clear # Clears all files in tmp/pids
rake tmp:sessions:clear # Clears all files in tmp/sessions
rake tmp:sockets:clear # Clears all files in tmp/sockets
</shell>
h5. +db:+ Database
The most common tasks of the +db:+ Rake namespace are +migrate+ and +create+, and it will pay off to try out all of the migration rake tasks (+up+, +down+, +redo+, +reset+). +rake db:version+ is useful when troubleshooting, telling you the current version of the database.
h5. +doc:+ Documentation
If you want to strip out or rebuild any of the Rails documentation (including this guide!), the +doc:+ namespace has the tools. Stripping documentation is mainly useful for slimming your codebase, like if you're writing a Rails application for an embedded platform.
h5. +notes:+ Code note enumeration
These tasks will search through your code for commented lines beginning with "FIXME", "OPTIMIZE", "TODO", or any custom annotation (like XXX) and show you them.
h5. +test:+ Rails tests
INFO: A good description of unit testing in Rails is given in "A Guide to Testing Rails Applications":testing.html
Rails comes with a test suite called Test::Unit. It is through the use of tests that Rails itself is so stable, and the slew of people working on Rails can prove that everything works as it should.
The +test:+ namespace helps in running the different tests you will (hopefully!) write.
h5. +time:+ Timezones
You can list all the timezones Rails knows about with +rake time:zones:all+, which is useful just in day-to-day life.
h5. +tmp:+ Temporary files
The tmp directory is, like the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions. The +tmp:+ namespace tasks will help you clear them if you need to if they've become overgrown, or create them in case of deletions gone awry.
h5. Miscellaneous Tasks
+rake 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.
+rake secret+ will give you a pseudo-random key to use for your session secret.
+rake 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.
|