Created
December 11, 2012 20:33
Aspect examples
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
class MyClass | |
simple: -> | |
alert "hello!" | |
another: -> | |
alert "hi!" | |
withParams: (a, b) -> | |
alert a + " - " + b | |
withReturnValue: (a) -> | |
return 2 * a | |
... | |
aspect MyClass, -> | |
@around 'simple', (jp) -> | |
alert "!!" | |
jp.proceed() | |
a = new MyClass | |
a.simple() | |
.... | |
# multiple aspects are also ok! these aspects could be in separate files | |
# not that the call order depends on execution order: latest advice is called first | |
aspect MyClass, -> | |
@around 'simple', (jp) -> | |
alert "!!" | |
jp.proceed() | |
aspect MyClass, -> | |
@around 'simple', (jp) -> | |
jp.proceed() | |
alert '??' | |
a = new MyClass | |
a.simple() | |
... | |
# we can add many advices in same aspect | |
aspect MyClass, -> | |
@around 'simple', (jp) -> alert '!!'; jp.proceed() | |
@around 'another', (jp) -> | |
# we can also "override" whole implementation | |
alert "overrided" | |
a = new MyClass | |
a.simple() | |
a.another() | |
... | |
# we can modify arguments | |
aspect MyClass, -> | |
@around 'withParams', (jp) -> | |
for i in [0..1] | |
jp.getArgs()[i] = "*#{jp.getArgs()[i]}*" | |
jp.proceed() | |
a = new MyClass | |
a.withParams("foo", "bar") | |
... | |
# we can also modify return values | |
aspect MyClass, -> | |
@around 'withReturnValue', (jp) -> | |
jp.proceed() | |
jp.setReturnValue Math.abs(jp.getReturnValue()) | |
a = new MyClass | |
alert a.withReturnValue(3) | |
alert a.withReturnValue(-3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment