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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With