Rails Console Cheatsheet

See All The Methods On A Class or Instance

irb(main):001:0> User.methods

This returns an array, which one can then do array things with, like filtering based on a pattern match

irb(main):001:0>  User.methods.grep(/string_pattern/)
NOTE: The [ Enumerable#grep ] method is super useful. Check out the ruby docs to see what it can do.

Or if you want a longer way of doing it…

irb(main):001:0>  User.methods.filter {|m| m.to_s.include?("string_pattern") }

Finding A Methods Source Location

If rails constants/contexts need to be loaded, then use rails console, otherwise use irb.

# Find the source location for a method called on an instance:
irb(main):001:0> user = User.new(name: "John", email: "john@email.com")
irb(main):001:0> user.method(:send_confirmation_instructions).source_location
=> ["/Users/etti/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/devise-4.8.1/lib/devise/models/confirmable.rb", 79]

# Find the source location for an instances method 
# but through its Class:
irb(main):001:0> User.instance_method(:confirm).source_location
=> ["/Users/etti/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/devise-4.8.1/lib/devise/models/confirmable.rb", 79]

Back in the normal shell, you can then use bundler to open the gems source code and then navigate to the file and line number obtained from the previous command

# This will open up your current version of the gem
bundler open devise
NOTE: To open up a gem's source code in general can run [ gem open gem_name ] or [ bundle open gem_name ] depending on what tool is managing the dependency.

Or if you want to do it an uglier waym, in the normal shell, you can take the path output, use an editor like vscode to open up the source code file and then head down to the line number given.

code /Users/etti/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/devise-4.8.1/lib/devise/models/confirmable.rb

References

Rails console deep dive

git, cheatsheet