我目前正在开发我的第一个 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
在这里使用正确的方法吗?- 选项哈希被传递到类方法中,并在实例方法体中使用。这安全吗?有记忆问题吗?