RubyistたちのDRY症候群との戦い Rubyで自動的にインスタンス変数をセットする を見て、Method#parameters と Module#prepend でそれをやるサンプル。
class Module
def auto_init *vars
m = self.instance_method(:initialize)
mod = Module.new do
define_method(:initialize) do |*args|
m.parameters.each_with_index{|(_, name), i|
if vars.include? name
instance_variable_set(:"@#{name}", args[i])
end
}
super(*args)
end
end
self.prepend mod
end
end
class Foo
attr_reader :x, :y
def initialize x, y, z; end
auto_init :x, :y
end
foo = Foo.new(1, 2, 3)
p [foo.x, foo.y]
:x, :y が並んでいるのが DRY じゃないけど、attr_reader をなんかうまくすれば、1セットは削れます。
http://regional.rubykaigi.org/tochigi05 で "Ruby 2.1 のすべて" というタイトルで発表させてもらいました。
資料はこちら:http://www.atdot.net/~ko1/activities/toruby05-ko1.pdf
めでたい!
おめでとうございます!
おおーなんと、おめでとうございます。