Class: Cut
Overview
Cut
Cuts are transparent subclasses. They are the basis of Cut-based AOP. The general idea of Cut-based AOP is that the Cut can serve a clean container for customized advice on top of which more sophisticated AOP systems can be built.
Examples
The basic usage is:
class X
def x; "x"; end
end
cut :Z < X do
def x; '{' + super + '}'; end
end
X.new.x #=> "{x}"
One way to use this in an AOP fashion is to define an aspect as a class or function module, and tie it together with the Cut.
module LogAspect
extend self
def log(meth, result)
...
end
end
cut :Z < X do
def x
LogAspect.log(:x, r = super)
return r
end
end
Implementation
Cuts act as a "pre-class". Which depictively is:
ACut < AClass < ASuperClass
Instantiating AClass effectively instantiates ACut instead, but that action is transparent.
A cut is a module that is prepended to its class, with Module#prepend. Given the following example:
class Klass
def x; "x"; end
end
cut :KlassCut < Klass do
def x; '{' + super + '}'; end
end
The effect is that of:
module KlassCut
def x; '{' + super + '}'; end
end
class Klass
prepend KlassCut
end
As it happens, Module#prepend is what Ruby took from the proposal for cuts. What a cut adds to it is a name for the idea and a record: a class knows its cuts, and a cut knows what it cuts.
Before Ruby had prepend, this library gave each new object its
class's cuts with extend, which missed objects that already
existed and those of subclasses.
Direct Known Subclasses
Constant Summary collapse
- VERSION =
The version of the Cuts library.
'2.0.0'
Instance Attribute Summary collapse
-
#base ⇒ Object
readonly
The class or module this cut is cut across.
Attributes inherited from Module
Instance Method Summary collapse
-
#initialize(base, &block) ⇒ Cut
constructor
Make a cut of a class or module.
Methods inherited from Module
Constructor Details
#initialize(base, &block) ⇒ Cut
Make a cut of a class or module. The block is the body of the cut.
Cut.new(X) do
def x; '{' + super + '}'; end
end
92 93 94 95 96 97 |
# File 'lib/cuts/cut.rb', line 92 def initialize(base, &block) @base = base super(&block) base.cuts.unshift(self) base.__send__(:prepend, self) end |
Instance Attribute Details
#base ⇒ Object (readonly)
The class or module this cut is cut across.
100 101 102 |
# File 'lib/cuts/cut.rb', line 100 def base @base end |