Rails Console Cheatsheet

Back

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]

In the normal shell, you can take the path output, use 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

Or open up the entire library’s directory with vscode and then navigate to the specific source location.

This allows you to follow the code to find other places along the code path you might be interested in.

code /Users/etti/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/devise-4.8.1/lib/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.

References

Rails console deep dive

· git , cheatsheet