Ruby:Meta-class和Class Variables

Ruby:Meta-class和Class Variables,第1张

概述我一直在看一些说 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 d 我一直在看一些说 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  endendputs 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   endend

这类似于

class Foo  def self.boo #class method  endend

同样,您可以抓取一个单独的对象并使用方法扩展它

class << some_object   def something # adds a method to some_object ONLY   endend

所以,当你在一个类定义中做“自我类”时,你会跳“一级”
进入你的“特征”类(或“元类”)的定义,你可以在上下文中调用东西
你的“阶级作为我所在的事物的一个例子”.所以类的方法
你的类成为实例方法,可以这样定义和处理,并且
模块包含会影响类方法没有实例方法.

对于你的情况:

class Joe  # here we're putting methods in the "class of class"  class << self    include ClassMethodsForJoe    attr_accessor :foo  endendJoe.foo # this is the method we made
总结

以上是内存溢出为你收集整理的Ruby:Meta-class和Class Variables全部内容,希望文章能够帮你解决Ruby:Meta-class和Class Variables所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1259989.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存