---
title: "关于Ruby Aop的小试验"
author: "nacu"
date: "2007-06-21T13:49:12Z"
tags: ["AOP", "ActiveRecord", "Google", "Ruby", "编程"]
slug: "ruby-aop"
draft: false
lastmod: "2007-06-21T13:49:12Z"
id: 92753
url: "https://nacu.iteye.com/blog/92753"
---

Ruby 的Metaclass功能确实强大,  
我仿照Rail的处理的做了一个Aop 的小试验,代码如下:

ruby 代码

 

01. # aop\_test.rb
02. # 2007年6月18日
03. \#
04. module AopAspects
05. def log\_method(\*args)
06. puts "log here"
07. args.each do |arg|
08. puts arg.to\_s
09. end
10. end
11. def trans\_aspect(\*args)
12. puts "trans here"
13. end
14. end
15. module AopBinder
16. def self.included(c)
17. c.extend(AopGenerate)
18. end
19. module AopGenerate
20. def run\_before(method,\*aspects)
21. alias\_method "#{method}\_old".to\_sym, method
22. before\_method = ""
23. aspects.inject("") {|before\_method,aspect| before\_method&lt;&lt;(aspect.to\_s + "(\*args)\\n")}
24. class\_eval &lt;&lt;-END
25. def #{method}(\*args)
26. #{before\_method}
27. #{method}\_old(\*args)
28. end
29. END
30. end
31. def run\_after(method,\*aspects)
32. alias\_method "#{method}\_old".to\_sym, method
33. before\_method = ""
34. aspects.inject("") {|before\_method,aspect| before\_method&lt;&lt;(aspect.to\_s + "(\*args)\\n")}
35. class\_eval &lt;&lt;-END
36. def #{method}(\*args)
37. #{method}\_old(\*args)
38. #{before\_method}
39. end
40. END
41. end
42. end
43. end
44. class AopTest
45. include AopAspects
46. include AopBinder
47. def initialize
48. end
49. def run
50. puts "hello, my run"
51. end
52. def run2(name="")
53. puts "hello, #{name}"
54. end
55. run\_before :run ,:log\_method
56. run\_after :run2 , :log\_method ,:trans\_aspect
57. end
58. a = AopTest.new
59. a.run
60. a.run2("ben")

结果如下  
log here  
hello, my run  
hello, ben  
log here  
ben  
trans here

充分体现了Ruby 简洁锐利的原编程风格