AOP¶
Aspect Oriented Programming. You can read about AOP at http://en.wikipedia.org/wiki/Aspect_oriented_programming.
Sapphire and AOP¶
I plan on supporting a limited form of AOP in Sapphire. I will not, however, adopt some of the more byzantine syntax that languages like Java have. Instead, I will support AOP in two ways. First, by redefining the semantics of super so that it looks at its containing singleton class first, then up the inheritance hierarchy. Second, by providing Object#pre, Object#post and Object#wrap methods as shortcuts.
Redefining super¶
Currently in Ruby the super method only looks up the inheritance hierarchy. In Sapphire, it will check its containing singleton first. For example:
class String
def size
puts "42" # pre
super
end
end
"hello".size # Prints "42", then returns the size, 5.
Object#pre, Object#post, Object#wrap¶
In Sapphire the Object class will define special methods for handling AOP in a more uniform fashion. For example, the following code would be functionally identical to the above example:
class String
def pre(:size)
puts "42"
end
end
"hello".size # Prints "42", then returns the size, 5
The Object#post method is similar to Object#pre, except that it fires after the method in question. For example:
class String
def post(:size)
puts "Howdy"
end
end
"hello".size # 5, followed by "howdy"
The Object#wrap is a combination of Object#pre and Object#post in that it fires both before and after the method. For example:
class String
def wrap(:size)
puts "It's a wrap!"
end
end
"hello".size # "It's a wrap", followed by 5, followed again by "It's a wrap"
Global AOP¶
To apply Object#pre to all methods of a given class, simply don't provide any arguments. For example:
class String
def pre
puts "All for one!"
end
end
"hello".size # prints "All for one!", then returns 5
"hello".include?("e") # prints "All for one!", then returns true
And so on. This would probably be unwise in practice.