ruby声明式语法的实现例子
在ActiveRecord可以用很方便的声明方式来定义model之间的关联关系,例如:
classTopic<ActiveRecord::Base has_many:posts belongs_to:user end
has_many和belongs_to其实是Topic类的classmethod,标准写法是:
classTopic<ActiveRecord::Base Topic.has_many(:posts) Topic.belongs_to(:user) end
那么has_many可以给我们带来什么呢?类方法has_many在被执行的时候,给Topic的对象实例添加了一系列方法:posts,posts<<,orders.push......等等。所以当我们在model里面声明has_many,belongs_to等对象关系的时候,一系列相关的对象方法就被自动添加进来了。让我们来自己试试看吧:
moduleM defself.included(c) c.extend(G) end moduleG defgenerate_method(*args) args.eachdo|method_name| define_method(method_name){putsmethod_name} end end end end
classC includeM generate_method:method1,:method2 end
c=C.new c.method1 c.method2