Is there a way to wrap all methods defined in my own namespace with a around/before/after filter such that I can log call occurrences and unused methods?
Asked
Active
Viewed 207 times
-7
-
1This pattern is usually called "aspect-oriented programming"; searching for Ruby and that should give you a number of different gems you can use; for example, Aspector or Aquarium should be able to do what you want. – Amadan Feb 03 '17 at 00:17
-
3Possible duplicate of [Executing code for every method call in a Ruby module](http://stackoverflow.com/questions/5513558/executing-code-for-every-method-call-in-a-ruby-module) – Grisha Levit Feb 03 '17 at 06:05
1 Answers
1
There's quite a bit of work to do to do what you want. Fortunately, you're not the only person that wants it, and it's been done before (as I said in comments, under "aspect-oriented programming".
Here's an example using the Aspector gem:
#!/usr/bin/env ruby
require 'aspector'
watcher = Aspector do
around(/.*/, except: Object.methods) do |proxy, *args, &block|
puts "before #{proxy.name} on #{proxy.receiver}"
proxy.call(*args, &block)
puts "after #{proxy.name} on #{proxy.receiver}"
end
end
class Foo
def self.klass
puts "class method"
end
def inst
puts "instance method"
end
end
watcher.apply(Foo)
watcher.apply(Foo, class_methods: true)
# => before singleton_method_added on Foo
# after singleton_method_added on Foo
Foo.klass
# => before klass on Foo
# class method
# after klass on Foo
Foo.new.inst
# => before inst on #<Foo:0x007f9b648c83c0>
# instance method
# after inst on #<Foo:0x007f9b648c83c0>

Amadan
- 191,408
- 23
- 240
- 301