最快/单行方式在Ruby中列出attr_accessors? [英] Fastest/One-liner way to list attr_accessors in Ruby?

查看:63
本文介绍了最快/单行方式在Ruby中列出attr_accessors?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

列出用attr_accessor定义的所有方法的最短单线方法是什么?我想这样做,如果我有一个类MyBaseClass,对它进行扩展的话,我可以在子类中获得attr_accessor的定义.像这样:

What's the shortest, one-liner way to list all methods defined with attr_accessor? I would like to make it so, if I have a class MyBaseClass, anything that extends that, I can get the attr_accessor's defined in the subclasses. Something like this:

class MyBaseClass < Hash
  def attributes
    # ??
  end
end

class SubClass < MyBaseClass
  attr_accessor :id, :title, :body
end

puts SubClass.new.attributes.inspect #=> [id, title, body]

仅显示attr_readerattr_writer定义会怎样?

推荐答案

无法(单行或其他方式)列出attr_accessor定义的所有方法,并且仅列出attr_accessor定义的方法而不定义自己的attr_accessor.

There is no way (one-liner or otherwise) to list all methods defined by attr_accessor and only methods defined by attr_accessor without defining your own attr_accessor.

这是一个覆盖MyBaseClass中的attr_accessor的解决方案,以记住使用attr_accessor创建了哪些方法:

Here's a solution that overrides attr_accessor in MyBaseClass to remember which methods have been created using attr_accessor:

class MyBaseClass
  def self.attr_accessor(*vars)
    @attributes ||= []
    @attributes.concat vars
    super(*vars)
  end

  def self.attributes
    @attributes
  end

  def attributes
    self.class.attributes
  end
end

class SubClass < MyBaseClass
  attr_accessor :id, :title, :body
end

SubClass.new.attributes.inspect #=> [:id, :title, :body]

这篇关于最快/单行方式在Ruby中列出attr_accessors?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆