您可以传递完整的属性而不是指定“名称”:
def to_json(*a)
{ 'json_class' => self.class.name, 'data' => attributes }.to_json(*a)
end
如果要过滤到特定属性,可以这样做:
def to_json(*a)
attrs_to_use = attributes.select{|k,v| %[name other].include?(k) }
{ 'json_class' => self.class.name, 'data' => attrs_to_use }.to_json(*a)
end
如果您只想使用“名称”,请写出来:)
def to_json(*a)
{ 'json_class' => self.class.name, 'data' => {:name => name} }.to_json(*a)
end
更新
为了阐明如何使初始化程序来处理所有属性,您可以执行以下操作:
class Person
attr_accessor :name, :other
def initialize(object_attribute_hash = {})
object_attribute_hash.each do |k, v|
public_send("#{k}=", v) if attribute_names.include?(k)
end
end
def attribute_names
%[name other] # modify this to include all publicly assignable attributes
end
def attributes
attribute_names.inject({}){|m, attr| m[attr] = send(attr); m}
end
def self.json_create(o)
new(o['data'])
end
def to_json(*a)
{ 'json_class' => self.class.name, 'data' => attributes }.to_json(*a)
end
end