Rails console tricks

Posted . Visible to the public.

Also see the list of IRB commands Show archive.org snapshot .

Switching the context

Changes the "default receiver" of expressions. Can be used to simulate a "debugger situation" where you are "inside" an object. This is especially handy when needing to call private methods – just invoke them, no need to use send.

  • Switch to an object: chws $object
  • Reset to main: chws
  • Show current context: cwws (usually shown in IRB prompt)

Technical details Show archive.org snapshot in a blog post from Doximity.

Printing object information

ls $object lists constants, ancestors with their methods, variables etc.

Adding console helper methods

# config/initializers/console.rb
Rails.application.console do
  def custom_helper
    ...
  end
end

Generating paths

  • app.root_path

Making requests

app.host = 'localhost'
app.get app.root_path
app.response.status
app.response.parsed_body

Using helpers

  • helper.some_helper_method

Examining the database schema

  • List tables: ActiveRecord::Base.connection.tables
  • List columns: ActiveRecord::Base.connection.columns($table_name)
Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2025-01-15 06:58)