Skip to content

Instantly share code, notes, and snippets.

@stadniklksndr
Last active April 6, 2022 07:24
Show Gist options
  • Save stadniklksndr/99c26e889ae4e83984290c6c239eb980 to your computer and use it in GitHub Desktop.
Save stadniklksndr/99c26e889ae4e83984290c6c239eb980 to your computer and use it in GitHub Desktop.

WiW

eileencodes, kamipo

* activerecord
* activerecord/lib/active_record/persistence.rb

Inspecting

Inspect the instance method:

  • User.instance_method(:name).source_location => ["/app/models/user.rb", 2]

Inspecting the class method:

  • User.singleton_method(:human?).source_location => ["/app/models/user.rb", 8]

Inspect helper method:

By default, the helper object is available in the console. On this object, you can call any helper method you defined in files placed inside app/helpers directory.

All methods you can use inside views are also available via the helper object.

  • helper.full_name("John", "Doe")

Inspect any class or object

You can get an excellent output containing variables, methods, and other information about a given object or class by using the ls function and passing this object (or class)

ls User.last

Inspect path:

By default, the app object is available in the console. This object represents the whole application. If you can execute on it all the paths that you have defined in routes.

  • app.articles_path(id: 1) => "/articles/1"
  • you can perform the request
app.host = "localhost"
app.get(app.articles_path(id: 1))

When the request is completed, you can inspect app.response to see the response body and status:

app.response.status # => 200
app.response.body # => "..."

If you don't set the host to localhost, your request will be blocked due to the not authorized host, which is set to www.example.com by default.

Inspecting rake tasks

In the console, we can invoke this rake task. The first step is to load all rake tasks:

Rails.application.load_tasks

and then we can invoke it in the following way:

Rake::Task['namespace:task'].invoke
Rake::Task['users:truncate'].invoke

Rendering the source of method

Render instance method:

  • User.instance_method(:name).source.display

Render class method:

  • User.singleton_method(:human?).source.display

Searching for methods

Search instance methods:

  • User.instance_methods.grep(/name$/) => [:name, :model_name, :class_name]

Search class methods:

  • User.singleton_methods.grep(/table_name$/) => [:schema_migrations_table_name]

Sandbox mode

The sandbox mode allows you to run the console in a special mode that will rollback all changes you made to the database when you exit from the console.

  • rails c –sandbox

You can now perform any action you want, but all changes will automatically roll back when you type exit in the console.

Switch the current context

You can change the console context to the object (or class) and then call the methods or attributes directly:

irb user
first_name
# => "John"
do_something
# => false
do_something_else
# => true

You can quickly exit the current context by writing exit.

Accessing the last returned value in console

The floor character would give you the latest value printed in the console

3.1.0 :001 > 2 + 2
=> 4
3.1.0 :002 > _
=> 4

Output object in the YAML format

You can debug a given object in a YAML format by passing it to the y method provided by the Kernel module

names = ["Tim", "John", "Tom"]
y names

The method is handy when debugging hashes with many pairs as well.

Make your own methods available in the console by default

To do this, you have to update config/application.rb and make the following change:

module MyProject
  class Application < Rails::Application
    console do
      module MyProjectConsole
        def report_user
          User.find(17623)
        end
      end
      Rails::ConsoleMethods.include(MyProjectConsole)
    end
  end
end

Next time you will load the console, you can just simply use report_user

SQL query

Quickly execute any SQL query against your database

sql = "SELECT * FROM users"
ActiveRecord::Base.connection.execute(sql)

Inspecting tables in the database

ActiveRecord::Base.connection.tables

Inspecting columns in the table

ActiveRecord::Base.connection.columns("users")

Silence SQL logs when executing queries

Rails provides simple logs wrapper that can silence all logs:

ActiveRecord::Base.logger.silence do
  User.find_each { |u| u.touch }
end

With the above version, no longs will be printed inside the console.

Use Greater Than/Less Than in Active Record where Statements

.where('day_of_week = ? AND range_end <= ?', day.wday, end_date)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment