Output local variables in real-time as they're defined?

Viewed 21

Is there a way to automatically output variable names and values to Rails logs as they're defined?

For example:

company_count = Company.count
person_count = Person.count

Instead of doing something like logger.debug for each line, can we set up some method that automatically outputs something like the following as each line is processed?

company_count set to 12
person_count set to 9
1 Answers

You can get such array using local_variables and eval

local_variables.map { |var| "#{var} set to #{eval(var.to_s)}" }

Keep attention, in the irb, pry or other interactive console local_variables could contain some "system" local variables and you need to filter this array (if you run separate ruby file.rb you don't need it). For example, local_variables.grep_v(/_/)

You can use this idea with logger. I don't sure you need to log local variables everywhere

You can call it as

local_variables.each { |var| Rails.logger.debug("#{var} set to #{eval(var.to_s)}") }
Related