Ruby:Meta-class和Class Variables
发布时间:2020-12-17 01:51:58 所属栏目:百科 来源:网络整理
导读:我一直在看一些说 class variables are bad in Ruby的文章.他们建议使用元类(或单例类).这是我的示例代码 class Joe class self # here we're putting methods in Joe's "meta class" attr_accessor :foo end def self.foo2 end def self.foo2=value endendp
我一直在看一些说
class variables are bad in Ruby的文章.他们建议使用元类(或单例类).这是我的示例代码
class Joe class << self # here we're putting methods in Joe's "meta class" attr_accessor :foo end def self.foo2 end def self.foo2=value end end puts Joe.singleton_methods 我知道foo和foo2基本相同,但是没有办法将attr_accesor与foo2一起使用. 我没有得到类<<<<<<自我语法.是否有某种连接发生,或者......它是什么?这是某种扩展,继承还是猴子修补? 编辑(奖金):虽然我在这里,有没有办法在视图助手上缓存数据?我尝试过使用这个类<<自我的东西,但帮助方法找不到访问者. 解决方法
等级<< foo语法代表“在foo类的定义中”.所以,如果你这样做:
class Foo class << self # class method defined as INSTANCE method # the only instance being Foo (the class) def boo ... end end end 这类似于 class Foo def self.boo #class method end end 同样,您可以抓取一个单独的对象并使用方法扩展它 class << some_object def something # adds a method to some_object ONLY end end 所以,当你在一个类定义中做“自我类”时,你会跳“一级” 对于你的情况: class Joe # here we're putting methods in the "class of class" class << self include ClassMethodsForJoe attr_accessor :foo end end Joe.foo # this is the method we made (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |