Slides from a talk I gave about using the Ruby on Rails console (and irb) to develop Web applications. Describes the features of the console, and how you might want to use it.
12. The Ruby way
Write in
Test IDE
fails?
Write a
test
Try in
console
13. The Ruby way
Write in
Test IDE
fails?
Write a Done? Try in
test browser
Try in
console
14. The Ruby way
It worked!
Write in
Test IDE
fails?
Write a Done? Try in
test browser
Try in
console
15. The Ruby way
Read logs,
backtrace
It worked!
Write in
Test IDE
fails?
Write a Done? Try in Failed? Try in
test browser console
Try in
console
Debugger
16. Whoa, that’s a lot!
• The idea is that the code is an extension of
your thoughts
• By “swimming through” and “playing with”
the code, you understand it better, and can
work with it faster
17.
18.
19. irb
• Interactive Ruby! (Comes with Ruby)
• Fire it up, and type Ruby code
• Define variables, classes, modules, methods
• All definitions disappear when you exit
• (Except for persistent storage, of course)
20. Why use irb?
• Test code
• Debug code
• Try things out
• Better understand Ruby
• Better understand an object or class
21. Rails requires more
• development/test/production environments
• ActiveRecord
• Other libraries, such as ActiveSupport
• HTTP requests and responses
• Model and controller objects
• Included gems
22. script/console
• Wrapper around irb
• Loads objects that are useful
• Makes other objects easily available
• Test your code, data, and assumptions
24. When?
• Always.
• It’s very rare for me to work on a Rails
project without a console open
• The console is where I test my objects,
experiment with code that’s longer than
one line, and try to debug my code
25. Simple IRB stuff
• Enter any Ruby code you want!
• Result of evaluation is displayed on the
screen
27. Printing vs. value
>> puts "hello"
hello
=> nil
>> ['foo', 'bar', 'baz'].each do |word|
?> puts word
>> end
foo
bar
baz
=> ["foo", "bar", "baz"]
28. Printing vs. value
>> puts "hello" This is what it prints
hello
=> nil
>> ['foo', 'bar', 'baz'].each do |word|
?> puts word
>> end
foo
bar
baz
=> ["foo", "bar", "baz"]
29. Printing vs. value
>> puts "hello" This is what it prints
hello
=> nil This is its value
>> ['foo', 'bar', 'baz'].each do |word|
?> puts word
>> end
foo
bar
baz
=> ["foo", "bar", "baz"]
30. Printing vs. value
>> puts "hello" This is what it prints
hello
=> nil This is its value
>> ['foo', 'bar', 'baz'].each do |word|
?> puts word
>> end
foo This is what it prints
bar
baz
=> ["foo", "bar", "baz"]
31. Printing vs. value
>> puts "hello" This is what it prints
hello
=> nil This is its value
>> ['foo', 'bar', 'baz'].each do |word|
?> puts word
>> end
foo This is what it prints
bar
baz
=> ["foo", "bar", "baz"]
This is its value
33. Multi-line irb
Open a class
irb(main):001:0> class Blah
irb(main):002:1> def sayit
irb(main):003:2> puts "hi"
irb(main):004:2> end
irb(main):005:1> end
=> nil
34. Multi-line irb
Open a class
irb(main):001:0> class Blah
irb(main):002:1> def sayit (Re)define a method
irb(main):003:2> puts "hi"
irb(main):004:2> end
irb(main):005:1> end
=> nil
35. Multi-line irb
Open a class
irb(main):001:0> class Blah
irb(main):002:1> def sayit (Re)define a method
irb(main):003:2> puts "hi"
irb(main):004:2> end
irb(main):005:1> end
=> nil Notice the prompt, showing line
numbers and block levels
36. Multi-line irb
Open a class
irb(main):001:0> class Blah
irb(main):002:1> def sayit (Re)define a method
irb(main):003:2> puts "hi"
irb(main):004:2> end
irb(main):005:1> end
=> nil Notice the prompt, showing line
Returns nil numbers and block levels
38. Variable assignment
• It works perfectly!
• Local, instance variables both work — but
instance variables don’t buy you anything
• Except namespace conflict avoidance
• Assignments disappear when irb exits
42. Inspecting objects
• Just type the object’s name
>> @bob
=> #<User:0x2645874
@new_record=true,
@attributes={"name"=>"Bob",
"job"=>"Test Dummy"}>
• notice instance variables and attributes
44. Classes, modules, and
methods
• You can define any or all of these
• Definitions work, and stick around for the
duration of the irb session
• Invisible to your running application
• When you exit, the definitions disappear
46. Defining classes
>> class Train
>> attr :passengers
>> def initialize
>> @passengers = [ ]
>> end
>> end Class definitions evaluate to nil
=> nil
>> t = Train.new
=> #<Train:0x102f391e0 @passengers=[]>
>> t.passengers << 'Reuven'
=> ["Reuven"]
>> t.passengers << 'Atara'
=> ["Reuven", "Atara"]
47. Define a new
ActiveRecord class
>> class Blah < ActiveRecord::Base
>> end
=> nil
>> Blah.first
ActiveRecord::StatementInvalid: RuntimeError: ERROR
C42P01 Mrelation "blahs" does not exist P15
Fparse_relation.c L857 RparserOpenTable:
SELECT * FROM "blahs" LIMIT 1
48. Define a new
ActiveRecord class
>> class Blah < ActiveRecord::Base
>> end
=> nil
Runtime message binding
>> Blah.first
ActiveRecord::StatementInvalid: RuntimeError: ERROR
C42P01 Mrelation "blahs" does not exist P15
Fparse_relation.c L857 RparserOpenTable:
SELECT * FROM "blahs" LIMIT 1
49. Avoiding huge output
• Person.all will return many records — and
thus print many records
• Assignment returns the assigned value
• Put a “;nil” after your command, and it’ll
evaluate to null, without any output!
•@people = Person.all; nil
50. Made a mistake?
• Use control-c to return to the top level
>> ['foo','bar','bat'].each do |word|
?> [1,2,3].each do |num|
?> ^C
>>
52. ActiveRecord
• ActiveRecord classes are available
• Console talks to the database for the
current environment
• Type the name of a class to see its fields
• Use class methods
• Create instances, use instance methods
55. Named scopes
• If you have a named scope:
named_scope :created_since, lambda
{ |since| { :conditions =>
['created_at >= ? ', since] }}
• Then it’s available as a class method, and we
can run it from inside of the console
>> Node.created_since('2010-9-1')
56. Huh? Named scopes?
• Don’t worry — we’ll get to those in an
upcoming session
• They’re really great, though!
58. Method differences
>> @p.save
=> false
>> @p.save!
ActiveRecord::RecordInvalid: Validation failed: First
name can't be blank, Last name can't be blank, Email
address can't be blank, Email address - Invalid email
address, Password can't be blank
60. Reloading
reload!
• Do this every time you change a model
• You will probably have to re-create instances
of ActiveRecord objects
• Otherwise, odd things can happen
61. Fat models =
easier testing
• ActiveRecord methods are immediately
available in the console
• This means that you can test your code
more easily when it’s in ActiveRecord
• Fat models win again!
• Remember: Keep your controllers skinny
62.
63. Sandbox
• script/console production --sandbox
• Reverts all changes that you made to the
database
• Allows you to work on your production
database without having to worry that
you’ll destroy things
64. Helpers
• Helpers: Methods for use within views
• Available under the “helper” object
• There are lots of helpers, and they have lots
of options. Test them before they’re in your
views!
71. Look at the response
>> app.get '/account/login'
=> 200
>> app.response.response_code
=> 200
>> app.response.body[0..100]
=> "<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"n "http://www.w3.org/TR/
xhtml1"
>> app.response.has_flash?
=> false
72. ri
• Get documentation from within irb/console:
>> ri 'String#new'
>> ri 'String#length'
• Works really nicely, but it can take a long
time to execute
73. .irbrc
• Code is executed every time you run IRB
or console
• If a line causes trouble, it silently fails and
stops reading the file
• Yes, this is really dumb
• Great for loading files, configuration
settings
74. Naming .irbrc in Win32
• Name the file whatever you want
• Set the environment variable IRBRC to
point to that file
• Done!
75. IRB configuration
• IRB (and the console) is an essential tool
• There are many configuration parameters
and gems you can use to enhance it
• They’re great!
76. Configuration in Ruby!
• IRB.conf is a hash
• Set elements of this hash in .irbrc to change
the configuration
87. Summary
• Use the console!
• The more you use the console, the more
comfortable you’ll feel with Ruby
• It will save you lots of time and effort
88. Inspiration
• Amy Hoy’s “slash7” blog (http://slash7.com/
2006/12/21/secrets-of-the-rails-console-
ninjas/)
• “Err the blog” posting “IRB mix tape” (http://
errtheblog.com/posts/24-irb-mix-tape)
• StackOverflow posting on “favorite IRB
tricks” (http://stackoverflow.com/questions/
123494/whats-your-favourite-irb-trick)
89. Contacting me
• Call me in Israel: 054-496-8405
• Call me in the US: 847-230-9795
• E-mail me: reuven@lerner.co.il
• Interrupt me: reuvenlerner (Skype/AIM)