3

Is there a way to get method parameters names and values dynamically, maybe a metaprogramming?

def my_method(name, age)
  # some code that solves this issue
end

my_method('John', 22) # => { name: 'John', age: 22 }

I want to use this in all my methods in order to log methods calls and respective parameters, but without to do this manually in every method.

Thanks.

Seralto
  • 1,016
  • 1
  • 16
  • 30

1 Answers1

5

Yup! In ruby, it's called the binding, which is an object that encapsulates the context in which a particular line runs. The full docs are here, but in the case of what you're trying to do...

def my_method(arg1, arg2)
  var = arg2
  p binding.local_variables #=> [:arg1, :arg2, :var]
  p binding.local_variable_get(:arg1) #=> 1
  p Hash[binding.local_variables.map{|x| [x, binding.local_variable_get(x)]}] #=> {:arg1 => 1, :arg2 => 2, :var => 2}
end

my_method(1, 2)

I'd strongly advise against Binding#eval, if you can possibly help it. There's almost always a better way to sovle problems than by using eval. Be aware that binding encapsulates context on the line at which it is called, so if you were hoping to have a simple log_parameters_at_this_point method, you'll either need to pass the binding into that method, or use something cleverer like binding_of_caller

ymbirtt
  • 1,481
  • 2
  • 13
  • 24