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
热门推荐
10 五一公司放假祝福语简短
11 追星女孩的祝福语简短
12 给长辈端午祝福语 简短
13 生日祝福语有诗意简短
14 团圆日祝福语简短
15 中秋商务祝福语简短最新
16 温暖文艺简短祝福语短句
17 男孩上学祝福语简短的
18 入住酒店文案祝福语简短