1

Here is an excerpt from my module:

module Helpers
  def self.reflect(callers_binding, callers_name)
    callers_method = caller_locations.first.label
    callers_instance = Module.const_get callers_name
    callers_parameters = callers_instance
      .method(callers_method)
      .parameters.map do |_, arg_name|
        [arg_name, callers_binding.local_variable_get(arg_name)]
      end
    callers_parameters = Hash[callers_parameters]
    puts "#{callers_instance}.#{callers_method}: #{callers_parameters}"
  end
end

module MyModule
  def self.foo(arg1, arg2)
    Helpers.reflect binding, self.to_s
    puts arg1, arg2
  end

  def self.bar(arg1, arg2, arg3)
    Helpers.reflect binding, self.to_s
    puts arg1, arg2, arg3
  end
end
  1. As seen, I would like to print a debug information using Helpers.reflect(). rather then writing explicitly in each function Helpers.reflect binding, self.to_s, is there any way to instruct ruby to execute Helpers.reflect binding, self.to_s before all functions in the module (except for Helpers.reflect itself) and avoiding writing it explicitly?
  2. How can Helpers.reflect() method be improved, providing less (or zero) argument to it?
Mr.
  • 9,429
  • 13
  • 58
  • 82
  • 1
    Can you provide one or more examples, showing desired return values? – Cary Swoveland Mar 21 '20 at 20:34
  • 1
    Something like [this](https://stackoverflow.com/questions/5513558/executing-code-for-every-method-call-in-a-ruby-module) ? – Karnaj Mar 21 '20 at 22:14
  • They're methods (not functions) in Ruby. [Ref](https://stackoverflow.com/q/8393331/3784008), [ref](https://stackoverflow.com/q/928443/3784008), [ref](https://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls). – anothermh Mar 22 '20 at 05:49
  • @Karnaj: thank you for the reference, although i haven't tried it, comments say it is not compatiable with ruby 2.7, and i couldn't understand how do i pass a variable to `before()` as i need to pass `binding` and `self.to_s`. i've updated my post – Mr. Mar 22 '20 at 07:47
  • @CarySwoveland: i've updated my question. would you kindly help? :) – Mr. Mar 22 '20 at 07:47

0 Answers0