For a Ruby on Rails developer, the Rails console is probably a familiar and indispensable tool in product development. The console helps interact with Rails applications, especially models, in real-time environments. Let's take a look at some tips to help us use rails console more effectively.
–sandbox
The Rails console has a mode called "sandbox". In this mode, all changes to the database will be restored when you exit the session.
1 2 | rails console --sandbox |
This is a great mode for you to freely test, update without affecting the data.
Get the value of the just-performed expression
Assuming you open the rails console:
1 2 | Job.first(10) |
The result is the first 10 job records. If you want to get this value you just need
1 2 | jobs = _ |
And then can use comfortably:
1 2 3 4 | job.size >> 10 ........ |
Or you can use "_" directly
1 2 3 | _.size >> 10 |
Search method with grep
You can look up the method name of an object if you remember part of its name. By using grep:
1 2 3 4 | first.methods.grep(/mail/) Job Load (0.7ms) SELECT `jobs`.* FROM `jobs` WHERE `jobs`.`active` = 1 ORDER BY `jobs`.`id` ASC LIMIT 1 => [:company_pic_email, :recruiter_email] |
Find out where the method is declared
The source_location
method of the Object class returns the full path where the method is declared. The results returned include the path to the file and the code that the method is declared. This method is especially useful when we want to dig into a 3rd party library
1 2 3 | "Test".method(:inquiry).source_location => ["/usr/local/bundle/gems/activesupport-4.2.1/lib/active_support/core_ext/string/inquiry.rb", 10] |
Returns the source code of a method
Above we know how to determine the exact location of a method. But we can even see its source code. This can be done via the object's source
method:
1 2 3 4 5 6 | "Test".method(:inquiry).source.display def inquiry ActiveSupport::StringInquirer.new(self) end => nil |
App object
The console provides an interesting object, which is the app object
. This is basically your miniature app. With this object, we can interact with the application as an HTTP client:
- GET
1 2 3 4 5 6 7 8 9 10 11 | >> app.get('/') Started GET "/" for 127.0.0.1 at 2019-12-20 06:31:23 +0000 DEBUG: Chewy strategies stack: [3] <- atomic @ /usr/local/bundle/bundler/gems/chewy-366cad2a457a/lib/chewy/railtie.rb:17 Processing by DashboardsController#index as HTML Rendered public/403.html (0.0ms) Filter chain halted as :check_access rendered or redirected Completed 403 Forbidden in 75ms (Views: 17.4ms | ActiveRecord: 0.0ms) DEBUG: Chewy strategies stack: [3] -> atomic @ /usr/local/bundle/bundler/gems/chewy-366cad2a457a/lib/chewy/railtie.rb:17 => 403 |
- Search for paths with
game
routers
1 2 3 | >> app.methods.grep(/_path/).grep(/game/) => [:search_games_path, :game_ownlist_placements_path, :game_ownlist_placement_path, :game_wishlist_placements_path, :game_wishlist_placement_path, :game_path] |
- Along a lot of interesting things you can explore