DEV Community

Cover image for Rails Command Line Tips and Tricks
John Finley
John Finley

Posted on

Rails Command Line Tips and Tricks

Working in Rails for me has been satisfying as I've learned the ins and outs. Going from not even knowing what an API to being able to build my own API with custom routes and relational tables has made it all feel worth it to me. Often I like to test my methods in the console but the data isn't always formatted very well. I'm going to share a couple ways to make the data more readable so that you can better understand your data.

For all of the following you are going to want to add the gem I've specified to your Gemfile and then run "bundle install". At the time of this writing I am using ruby "2.7.4" and rails "7.0.3".

Awesome Print

Add gem 'awesome_print' to Gemfile and bundle. After running "rails c" you can put "ap" before the object you want to call and it will print with full color and proper indentation.

> ap Movie.first
  Movie Load (0.2ms)  SELECT  "movies".* FROM "movies" ORDER BY "movies"."id" ASC LIMIT ?  [["LIMIT", 1]]
#<Movie:0x00000003fcf7f8> {
             :id => 1,
          :title => "Batman",
           :year => 1989,
          :genre => "Action, Adventure",
       :director => "Tim Burton",
     :production => "USA, Great Britain",
      :boxoffice => "$411 348 924",
    :description => "The Dark Knight of Gotham City begins his war on c...",
          :score => 7.6,
     :created_at => Sat, 23 Jul 2016 09:47:15 UTC +00:00,
     :updated_at => Sat, 23 Jul 2016 09:47:15 UTC +00:00
}
Enter fullscreen mode Exit fullscreen mode

Hirb

Add gem 'hirb' to Gemfile and bundle. After running "rails c" you need to enter "hirb.enable". Once you do that, your data will be presented in a nicely formatted table.

2.7.4 :002 > Hirb.enable
 => true 
2.7.4 :003 > Comment.all
  Comment Load (0.5ms)  SELECT "comments".* FROM "comments" ORDER BY "comments"."created_at" DESC                                               
+----+--------------------+---------+---------+--------------------+---------------------+
| id | body               | user_id | post_id | created_at         | updated_at          |
+----+--------------------+---------+---------+--------------------+---------------------+
| 2  | Great topic!       | 3       | 1       | 2022-09-16 02:3... | 2022-09-16 02:36... |
| 1  | You also do not... | 2       | 1       | 2022-09-16 02:3... | 2022-09-16 02:36... |
+----+--------------------+---------+---------+--------------------+---------------------+
2 rows in set     
Enter fullscreen mode Exit fullscreen mode

Conclusion

These are just a couple of ways that you can make your Rails table look a little more organized and easy to read. Give them a try in your next project. Are there any cool tips and tricks for the Ruby command line that you know of?

Top comments (0)