0
オブジェクト私は私のプロジェクトの一つでActiveModelを使用していると私は、動的メソッドのための最善の方法は、ActiveModel dymamic方法は
基本ActiveModelクラスのみ1つのアクセッサ属性が属性を呼び出した次のような状況で定義されたものをお聞きしたかったです。
def initialize(attributes = {})
set_default_attributes!
@attributes.merge!(attributes.symbolize_keys)
@new_record = true
end
def read_attribute_for_validation(key)
@attributes[key]
end
def self.create(attributes={})
obj = self.new(attributes)
obj.save
return obj
end
def save
if self.valid?
puts "saved!"
return true
end
return false
end
def update_attributes(attributes={})
self.attributes.merge!(attributes.symbolize_keys)
self.save
end
def as_json(options={})
hash = Hash.new
hash.merge!(self.attributes)
hash.as_json({:root=>false}.merge!(options || {}))
end
方法は、アクセッサのようでなければならないが、@attributes
がハッシュである場合{:param1=>1,:param2=>2}
インスタンス・オブジェクトは次のメソッドを
param1
param1=
param2
param2=
を有していなければならないように、私はしようとした可変
例内部@attributesを使用する必要がメソッドがありませんが、メソッドが "="で終わっている場合は、解析し、そのようなキーの属性をチェックする必要があります。コードの見た目が気に入らない。
とメソッドを追加することができます!これは正規表現で簡単にできるはずです。 – phoet
私はこれを行うことができますが、私はそれをより多くのルビーの方法にするためにdefine_methodを使いたいと思います – Fivell
define_methodを使うのはもっとルビー的な方法だとは思っていませんが、早くやれよ?! – phoet