私は現在、最初の gem に取り組んでおり、メタ プログラミングで初めての経験をしています。
したがって、クラス定義中にインスタンス メソッドを正しく定義する方法について、フィードバックをお願いします。
具体的には、次extend
のように ActiveRecord モデルで使用することになっているこのモジュールを作成しました。
class Duck < ActiveRecord::Base
extend UnitedAttributes::Model
attr_accessible :name, :weight
unite :weight, :kilogram
end
UnitedAttribues::Model
モジュールのソースはこちら。https://github.com/nielsbuus/united_attributes/blob/master/lib/united_attributes/model.rb
そして、これは余分なコードを除いた短縮版です:
module UnitedAttributes
module Model
def unite(accessor, unit, options = {})
class_eval do
define_method "united_#{accessor}" do
Attribute.new(self.send(accessor), options)
end
end
end
end
end
動作しているように見えますが、いくつかの懸念があります。
class_eval
ここで使用する正しい方法はありますか?define_method
ここで使用する正しい方法はありますか?- オプション ハッシュはクラス メソッドに渡され、インスタンス メソッド本体内で使用されます。これは安全ですか?メモリに関する懸念はありますか?