$ ruby thing.rb
[Calculator::LoggerDecorator, Calculator, Object, Kernel, BasicObject]
Calculator#div(10, 2) => 5
Last active
May 9, 2018 02:02
-
-
Save lucasmazza/91ae43bfea7e26782b0212ecb331ac15 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module MagicLog | |
def self.extended(receiver) | |
decorator = Module.new | |
receiver.prepend decorator | |
receiver.const_set(:LoggerDecorator, decorator) | |
end | |
def log(name) | |
self::LoggerDecorator.define_method(name) do |*args| | |
result = super(*args) | |
puts "#{self.class.name}##{name}(#{args.map(&:inspect).join(", ")}) => #{result}" | |
result | |
end | |
end | |
end | |
class Calculator | |
extend MagicLog | |
log :div | |
def div(x, y) | |
x / y | |
end | |
end | |
p Calculator.ancestors | |
Calculator.new.div(10, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment