Rails console shortcuts
Contact me at LinkedIn  RailsZilla at Facebook  RailsZilla at twitter   google +1  Contact me at Xing  connect me at github

Rails console shortcuts

Posted in console, Rails, Start

I always forget all those handy hints in Ruby on Rails, while using my Rails console. Here I will drop some very useful console commands to get some daily jobs done:

Hint No.1
Sometimes we change the code in a file. In that case we can reload the changes in the rails console by using the reload! method.

1
2
3
> reload!
Reloading...
 => true

Hint No.2
You can customize your IRB by creating an .irbrc in your home folder. Let’s open the Object class and define a method.

1
2
3
4
5
class Object
  def foo
    'bar'
  end
end

Now you can access the foo method in the rails console like this:

1
2
3
4
rails c
Loading development environment (Rails 5.0.0.beta3)
 > foo
 => "bar"

Hint No.3
We can print the yaml representation of an object very easy by using the y method.

1
2
3
4
5
6
$ rails c
p Loading development environment (Rails 5.0.0.beta3)
 > p = Post.first

Post Load (0.3ms)  SELECT  "post".* FROM "posts" ORDER BY "posts"."id" ASC LIMIT ?  [["LIMIT", 1]]
 => #<Post id: 1, name: "Foo", created_at: "2017-03-28 11:38:42", updated_at: "2076-06-29 12:12:45">

Now we just enter in the console

1
 > y p

and we get a nice view in YML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  id: 1
  name: Foo
  created_at: '2017-03-28 11:38:42'
  updated_at: '2076-06-29 12:12:45'
attributes: !ruby/object:ActiveRecord::AttributeSet
  attributes: !ruby/object:ActiveRecord::LazyAttributeHash
    types:
      id: &2 !ruby/object:ActiveModel::Type::Integer
        precision:
        scale:
        limit:
        range: !ruby/range
          begin: -2147483648
          end: 2147483648
          excl: true

... AND SO ON ...

Hint No.4
To have a better output, we ca use pretty print by entering pp into the console. This is much more readable than the yaml method.
We first have to require ‘pp’ if we use a Rails Version < Rails 5. Because pp is already required by Rails 5, we see the false output in our console when requiring it with Rails 5.

1
2
3
 > require 'pp'
 => false
 > pp p

Hint No.5
I often use autocomplete by typing the first few characters and then hitting the tab a few times.

1
2
3
4
2.3.0 :001 > Acti
ActionController  ActionPack        ActiveJob         ActiveSupport
ActionDispatch    ActionView        ActiveModel      
ActionMailer      ActiveAdmin       ActiveRecord

I will post some more in the next posting. Have fun.

Tags: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Please enter a secure code to see if you are a spammer ;-)

 

Copyright © 2011-2017  - RailsZilla – Ruby on Rails tutorials, tips and tricks All rights reserved. | Imprint | Privacy