属性が処理される方法でRails AactiveRecordモデルと同様に機能するRubyクラスを作成しようとしています:
class Person
attr_accessor :name, :age
# init with Person.new(:name => 'John', :age => 30)
def initialize(attributes={})
attributes.each { |key, val| send("#{key}=", val) if respond_to?("#{key}=") }
@attributes = attributes
end
# read attributes
def attributes
@attributes
end
# update attributes
def attributes=(attributes)
attributes.each do |key, val|
if respond_to?("#{key}=")
send("#{key}=", val)
@attributes[key] = name
end
end
end
end
つまり、クラスを初期化すると、「属性」ハッシュが関連する属性で更新されます。
>>> p = Person.new(:name => 'John', :age => 30)
>>> p.attributes
=> {:age=>30, :name=>"John"}
>>> p.attributes = { :name => 'charles' }
>>> p.attributes
=> {:age=>30, :name=>"charles"}
ここまでは順調ですね。私がしたいのは、個々のプロパティを設定したときに属性ハッシュを更新することです。
>>> p.attributes
=> {:age=>30, :name=>"John"}
>>> p.name
=> "John"
>>> p.name = 'charles' # <--- update an individual property
=> "charles"
>>> p.attributes
=> {:age=>30, :name=>"John"} # <--- should be {:age=>30, :name=>"charles"}
を使用する代わりに、すべての属性に対してセッターとゲッターを作成することでそれを行うことができますがattr_accessor
、それは多くのフィールドを持つモデルには適していません。これを達成する簡単な方法はありますか?