「名前」を指定する代わりに、完全な属性を渡すことができます。
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