Ruby:attr_accessor 生成的方法 - 如何迭代它们(以 to_s - 自定义格式)? [英] Ruby: attr_accessor generated methods - how to iterate them (in to_s - custom format)?
问题描述
我需要一个具有半自动to_s"方法的类(实际上用于生成 XML).我想遍历attr_accessor"行中设置的所有自动方法:
I need a Class which has an semi-automatic 'to_s' method (to generate XML in fact). I would like to iterate through all the automatic methods set up in my 'attr_accessor' line:
class MyClass
attr_accessor :id,:a,:b,:c
end
c=MyClass.new
到目前为止,我正在做一个基本的:
So far I'm doing a basic:
c.methods - Object.methods
=> ["b", "b=", "c", "c=", "id=", "a", "a="]
我面临一些挑战:
- 'id' 可能会引起轻微的头痛 - 因为 Object 似乎已经有一个 'id'.
- 上面的c.methods"调用返回字符串——我没有得到任何其他元数据?(在 Java 中,方法"是一个对象,我可以在其中执行进一步的反射).
- 我必须处理一对多关系('c' 是其他对象类型的数组类型).
这就是我想要做的:我想设计一个简单的对象,它有一个to_s",它将构建一个 XML 片段:例如.
This is what I'm trying to do: I want to design a simple Object which has a 'to_s' which will build up an XML fragment: for instance.
<id> 1 </id>
<a> Title </a>
<b> Stuff </b>
<c>
<x-from-other-object>
<x-from-other-object>
....
</c>
然后从那个简单的对象继承我的数据类:这样(希望)我得到一个机制来构建整个 XML 文档.
And then inherit my data-classes from that simple object: so that (hopefully) I get a mechansim to build up an entire XML doc.
我确定我也在重新发明轮子……所以欢迎使用其他久经考验的方法.
I'm sure I'm re-inventing the wheel here as well...so other tried-and-tested approaches welcome.
推荐答案
要从字符串中获取方法对象,可以使用方法 method
或 instance_method
(其中 method
将在对象上调用,instance_method
在类上调用).不过,它为您提供的唯一有趣的信息是 arity(与 java 不同的是,它还会为您提供返回值和参数的类型,这在 ruby 中当然是不可能的).
To get method objects from a string, you can use the methods method
or instance_method
(where method
would be called on an object and instance_method
on a class). The only interesting information it gives you is arity, though (as opposed to java where it'd also give you the types of the return value and the arguments, which of course isn't possible in ruby).
您的标题表明您只想迭代由 attr_accessor
创建的方法,但是您的代码将迭代您的类中定义的每个方法,如果您想添加额外的非-您的类的访问器方法.
Your title suggests that you only want to iterate over methods created by attr_accessor
, but your code will iterate over every method defined in your class, which could become a problem if you wanted to add additional non-accessor methods to your class.
为了摆脱那个问题和 id
的问题,你可以在 attr_accessor
周围使用你自己的包装器,它存储它为哪些变量创建了访问器,如下所示:
To get rid of that problem and the problem with id
, you could use your own wrapper around attr_accessor
which stores which variables it created accessors for, like so:
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
对于问题 3,你可以这样做
For problem 3 you can just do
if item.is_a? Array
do_something
else
do_something_else
end
这篇关于Ruby:attr_accessor 生成的方法 - 如何迭代它们(以 to_s - 自定义格式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!