Ruby:attr_accessor生成的方法 - 如何迭代它们(在to_s中 - 自定义格式)?

mon*_*nny 8 ruby xml reflection

我需要一个具有半自动'to_s'方法的类(实际上生成XML).我想遍历在'attr_accessor'行中设置的所有自动方法:

class MyClass
    attr_accessor :id,:a,:b,:c
end

c=MyClass.new
Run Code Online (Sandbox Code Playgroud)

到目前为止,我正在做一个基本的:

c.methods - Object.methods

=> ["b", "b=", "c", "c=", "id=", "a", "a="]
Run Code Online (Sandbox Code Playgroud)

我面临一些挑战:

  1. 'id'可能会引起轻微的头痛 - 因为Object似乎已经有了'id'.
  2. 上面的'c.methods'调用返回字符串 - 我没有得到任何其他元数据?(在Java'方法'中是一个对象,我可以在其中执行进一步的反射).
  3. 我有一对多的关系我必须处理('c'是其他对象类型的数组类型).

这就是我想要做的:我想设计一个简单的Object,它有一个'to_s',它将构建一个XML片段:例如.

<id> 1 </id>
<a> Title </a>
<b> Stuff </b>
<c>
    <x-from-other-object>
    <x-from-other-object>
    ....
</c>
Run Code Online (Sandbox Code Playgroud)

然后从这个简单的对象继承我的数据类:这样(希望)我得到一个mechansim来构建一个完整的XML文档.

我相信我也在这里重新发明轮子......所以其他久经考验的方法也值得欢迎.

sep*_*p2k 13

要从字符串中获取方法对象,可以使用方法methodinstance_method(在method对象和instance_method类上调用的位置).它给你的唯一有趣的信息是arity(与java相反,它也提供了返回值和参数的类型,这当然在ruby中是不可能的).

您的标题表明您只想迭代由其创建的方法attr_accessor,但您的代码将遍历您的类中定义的每个方法,如果您想在类中添加其他非访问方法,这可能会成为一个问题.

为了摆脱这个问题和问题id,你可以使用自己的包装器来attr_accessor存储它为其创建访问器的变量,如下所示:

module MyAccessor
  def my_attr_accessor *attrs
    @attrs ||= []
    @attrs << attrs
    attr_accessor *attrs
  end

  def attrs
    @attrs
  end
end

class MyClass
  extend MyAccessor
  my_attr_accessor :id,:a,:b,:c

  def to_s
    MyClass.attrs.each do |attr|
      do_something_with(attr, send(attr))
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

对于问题3,您可以这样做

if item.is_a? Array
  do_something
else
  do_something_else
end
Run Code Online (Sandbox Code Playgroud)