ruby强大的 define_method,有闭包的能力!
闭包的例子一般是在说ruby的块,特片是:访问本地变量和绑定运行上下文(很强大的两点)
?
class Metadata attr_accessor :relation_nameendmodule Accessor def build(name, metadata) p name, metadata, metadata.relation_name end module ClassMethods def getter(name, metadata) tap do define_method(name) do build( name, metadata ) end end end end end class Doc include Accessor extend Accessor::ClassMethodsendmeta = Metadata.newmeta.relation_name = 'embeds_one'Doc.getter("ss_car", meta)# p Doc.public_instance_methodsDoc.new.ss_carmeta2 = Metadata.newmeta2.relation_name = 'ref_one'Doc.getter("ss_bus", meta2)Doc.new.ss_bus
?
输出:
?
"ss_car"
#<Metadata:0x00000100846f38 @relation_name="embeds_one">
"embeds_one"
"ss_bus"
#<Metadata:0x00000100846128 @relation_name="ref_one">
"ref_one"
?
?
?
?