モンキーパッチのメタプログラミング-もっとエレガントにすることができるかもしれませんが、これは簡単なドラフトにすぎません。しばらくの間、メタプログラミングを行っていません...
# inject the convenience method into the definition of the Object class
class Object
def Object::bool_attr(attrname)
class_eval { define_method(attrname.to_s,
lambda { instance_variable_get('@' + attrname.to_s.chop) }) }
class_eval { define_method(attrname.to_s.chop+"=",
lambda { |x| instance_variable_set('@'+attrname.to_s.chop, x) }) }
end
end
### somewhere later
class MyClass
bool_attr :my_boolean_attribute?
def initialize
@my_boolean_attribute = true
end
end
# yet even more later
foo = MyClass.new
bar = MyClass.new
foo.my_boolean_attribute = 1
puts foo.my_boolean_attribute?
puts bar.my_boolean_attribute?
このアプローチを使用すると、DRYになり、素敵な疑問符を取得することもできます。「 bool_attr_accessor」など、「bool_attr 」よりも適切な名前を選択する必要がある場合があります。
私が作成した定義は、元のシンボルに疑問符が含まれているという意味で、少し不機嫌です。おそらく、よりクリーンなアプローチは、シンボル名の疑問符を避け、メソッドの定義中にそれを追加することです-混乱を少なくする必要があります。
ああ、そして義務的なリンクを含めるのをほとんど忘れていました:メタクラスをはっきりと見る