EDIT: I slightly changed the spec, to better match what I imagined this to do.
Well, I don’t really want to fake C# attributes, I want to one-up-them and support AOP as well.
Given the program:
class Object
def Object.profile
# magic code here
end
end
class Foo
# This is the fake attribute, it profiles a single method.
profile
def bar(b)
puts b
end
def barbar(b)
puts(b)
end
comment("this really should be fixed")
def snafu(b)
end
end
Foo.new.bar("test")
Foo.new.barbar("test")
puts Foo.get_comment(:snafu)
Desired output:
Foo.bar was called with param: b = "test" test Foo.bar call finished, duration was 1ms test This really should be fixed
Is there any way to achieve this?
I have a somewhat different approach:
A few points about this solution:
method_added) without the need for aliasing.class_evalrather thandefine_methodto define the new method in order to be able to support methods that take blocks. This also necessitated the use ofalias_method.profileorcommentis called, which is then applied when a method is added. As in the previous solution, themethod_addedhook is used to track when the new method is added, but instead of removing the hook each time, the hook checks for an instance variable. The instance variable is removed after the AOP is applied, so it only applies once. If this same technique was used multiple time, it could be further abstracted.