关于Ruby Aop的小试验
Ruby 的Metaclass功能确实强大,
我仿照Rail的处理的做了一个Aop 的小试验,代码如下:
ruby 代码
- # aop_test.rb
- # 2007年6月18日
- #
- module AopAspects
- def log_method(*args)
- puts "log here"
- args.each do |arg|
- puts arg.to_s
- end
- end
- def trans_aspect(*args)
- puts "trans here"
- end
- end
- module AopBinder
- def self.included(c)
- c.extend(AopGenerate)
- end
- module AopGenerate
- def run_before(method,*aspects)
- alias_method "#{method}_old".to_sym, method
- before_method = ""
- aspects.inject("") {|before_method,aspect| before_method<<(aspect.to_s + "(*args)\n")}
- class_eval <<-END
- def #{method}(*args)
- #{before_method}
- #{method}_old(*args)
- end
- END
- end
- def run_after(method,*aspects)
- alias_method "#{method}_old".to_sym, method
- before_method = ""
- aspects.inject("") {|before_method,aspect| before_method<<(aspect.to_s + "(*args)\n")}
- class_eval <<-END
- def #{method}(*args)
- #{method}_old(*args)
- #{before_method}
- end
- END
- end
- end
- end
- class AopTest
- include AopAspects
- include AopBinder
- def initialize
- end
- def run
- puts "hello, my run"
- end
- def run2(name="")
- puts "hello, #{name}"
- end
- run_before :run ,:log_method
- run_after :run2 , :log_method ,:trans_aspect
- end
- a = AopTest.new
- a.run
- a.run2("ben")
结果如下
log here
hello, my run
hello, ben
log here
ben
trans here
充分体现了Ruby 简洁锐利的原编程风格
谢谢hideto 学到了很多阿 这样确实实现了最大的灵活度
参考一下ActiveRecord的Callbacks,共有四种macros,分别为Method references(symbol)/Callback objects/Inline methods(proc)/Inline eval methods(string)
http://hideto.iteye.com/blog/93084
和下面的表述是一样的 class_eval(%Q) ruby 的语法还真是,实现同一种目的有n种表述方法,在项目应用中看来还是要制定一种表述约定,不然沟通和维护实在是不方便。
真的不好意思。能解释一下字符块么?或者给个链接 我google了 ruby 字符块 也没结果。
谢谢了
对阿 呵呵 没有想到 对于 block的使用还是不太习惯 这样的实现是最简洁的 按照ruby 的惯例 最后的使用应该是 run_before :method1 ,:method2 ...........{do something} run_after :method1 ,:method2 ...........{do something} run_around :method1 ,:method2 ...........{do something} 这样的描述吧
有了block不就可以调用任何地方的代码了么,随便你把要分离的代码放到哪里都可以啊,Class Method, module mixin进来都可以:
不好意思 <<->END 的表述不太好 可能用 class_eval <<->EOF def #{method}(*args) #{before_method} #{method}_old(*args) end EOF 更加好吧
表示一个字符块
这段代码没看懂
class_eval <<->END def #{method}(*args)
#{before_method}
#{method}_old(*args)
end
END
:(
END是啥?
谢谢 readonly 的回复阿 有个小小的疑惑,如果用run_before + block 确认可以省去很多的代码,不过这个切面的实现就被放到block中了。问题是,切面的代码放在哪里才是最合适的呢?是不是应该有个地方专门用来定义这个东西的。 随着代码量的增加,按照DRY的原则,是不是应该继续抽象这个切面的实现方式,放到某个module中呢。
偶觉得动态语言没有必要啥正儿八经的Aop框架,利用现成的hotswap,mixin,method_missing这些特性,来做关注分离是很简单的。