道喜技术日记 .^. 天天红玉世界

Rails Ruby MacOSX 。。。创新来自于刻苦的实践和勤奋的思考... www.hhtong.com


代码世界:Ruby/Rails反射技术实例

Gudao Luo2009-07-11 at 06:51发表的

Ruby/Rails反射技术实例
  • 使用正常类方法代码
@blogs = Blog.find(:all)
  • 使用反射技术代码(Ruby语言)
@blogs = Kernel.const_get("Blog").send(:find, :all)
@blogs = Object.const_get("Blog").send(:find, :all)
@blogs = Kernel.eval("Blog").send(:find, :all)
  • 使用反射技术代码(类名称包含”::”)(Ruby语言)
Model = "ActiveRecord::Base".split('::').inject(Object) do |base,item|
base.const_get(item)
end
class Blog < Model; end
  • 使用反射技术代码(Rails框架)
@blogs = "Blog".classify.constantize.send(:find, :all)
Hierarchy: previous, next

Comments

There are 0 comments on this post. Post yours →

Post a comment

Required fields in bold.