Skip to content

Instantly share code, notes, and snippets.

@milankinen
Created December 11, 2012 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milankinen/4261912 to your computer and use it in GitHub Desktop.
Save milankinen/4261912 to your computer and use it in GitHub Desktop.
Aspect examples
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