Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick way to see variables that apply in current scope and which object self refers to, RAILS

Is there a quick way to find out which variables apply with the current scope, and which object 'self' refers to in Ruby on Rails?

like image 208
Jordan Poulton Avatar asked Feb 24 '13 22:02

Jordan Poulton


People also ask

What happens when an object variable goes out of scope?

Nothing physical happens. A typical implementation will allocate enough space in the program stack to store all variables at the deepest level of block nesting in the current function. This space is typically allocated in the stack in one shot at the function startup and released back at the function exit.

What is debugger in Rails?

Let's start with the most straightforward option: Rails' own debug method. It can be used for displaying data for any object in the front end. This is helpful when something isn't showing properly on the website and you want to find out if it's missing in the database or it's an issue with the view code.

What are scopes in Ruby?

Scopes are custom queries that you define inside your Rails models with the scope method. Every scope takes two arguments: A name, which you use to call this scope in your code. A lambda, which implements the query.

Can you console log in Rails?

One of the best tools in a rails developers arsenal is the rails console, being extremely useful for brainstorming, debugging, and testing. Having it log active record queries directly to the console can improve readability and convenience over looking through the development logs to see what SQL queries have been run.


1 Answers

I think pry is a great solution, although debugger, as @jvnill suggested, also works.

gem install pry # or add to bundler

In your code you need to add the following wherever you are interested in inspecting the scope:

require 'pry'
binding.pry # this will open a console view with the binding as the current scope

In pry there is something built in for what you're asking:

pry> ls

ls will show variables and methods that can be called and from which objects/classes they originate.

pry> self # will return self in the current context
pry> pry-backtrace # shows the current stack
pry> help # will show the list of commands
pry> cd <some obj> # will change the scope to the target object
pry> exit # move back out to previous console scope

Clarify if you are looking for something entirely different.

like image 115
Matt Dressel Avatar answered Nov 10 '22 00:11

Matt Dressel