2003.05.01
import-module はモジュールのインクルードを動的に行います。
reqruire "import-method"
をするとModuleに以下のメソッドが
付け加えられます。
import_module(mod) { ... }
mod をモジュールとして取り込んだ状態で ... を実行します。
(例)
require "import-module" class Foo def hello puts 'hello' end end module Bar def hello puts 'bye' end end module Baz def hello puts 'good-bye' end end foo = Foo.new foo.hello #=> hello Foo.import_module(Bar) do foo.hello #=> bye Foo.import_module(Baz) do foo.hello #=> good-bye end foo.hello #=> bye end foo.hello #=> hello
adopt_module(mod)
mod をモジュールとして取り込みます。
(例)
require "import-module" class Foo def hello puts 'hello' end end module Bar def hello puts 'bye' end end foo = Foo.new Foo.adopt_module(Bar) foo.hello #=> bye
また、Objectには次のメソッドが付け加わります。
import(mod) { ... }
mod をモジュールとして取り込んだ状態で ... を実行します。
(例)
require "import-module" class Foo def hello puts 'hello' end end module Bar def hello puts 'bye' end end foo = Foo.new bar = Foo.new foo.hello #=> hello bar.hello #=> hello foo.import(Bar) do |foo0| foo.hello #=> bye p foo == foo0 #=> true bar.hello #=> hello end foo.hello #=> hello bar.hello #=> hello
adopt(mod)
mod をモジュールとして取り込みます。
(例)
require "import-module" class Foo def hello puts 'hello' end end module Bar def hello puts 'bye' end end foo = Foo.new bar = Foo.new foo.adopt(Bar) foo.hello #=> bye bar.hello #=> hello
このライブラリはマルチスレッド対応しています。
(例)
require "import-module" class Foo def hello puts 'hello' end end module Bar def hello puts 'bye' end end foo = Foo.new foo.hello #=> hello Thread.start do Foo.import_module(Bar) do foo.hello #=> bye end end foo.hello #=> hello
マルチスレッド対応が必要でない場合は、import-module.rb
ではなく、
import-module-single-thread.rb
を require してください。
メソッドの呼び出しが早くなります。
Enumerable の一時的な変更
require "import-module" module EachChar def each(&b); split(//).each(&b); end end p "abc".import(EachChar){|s| s.map{|x| x.succ}}.join("") #=> "bcd"
整数値行列をそのまま有理数値行列として扱う。
require "import-module" require "matrix" require "rational" module RationalDiv def /(other) Rational(self) / other end end a = Matrix[[2, 1], [3, 1]] puts a.det #=> 0 Fixnum.import_module(RationalDiv) do puts a.det #=> -1 end puts a.det #=> 0
RAA <URL:http://www.ruby-lang.org/en/raa.html> における以下のプログラムを参 考にしました。
0.78 (2002.11.05)
0.77 (2002.11.05)
0.76 (2002.11.01)
0.75 (2002.10.31)
0.74 (2002.10.30)
0.73 (2002.10.28)
0.72 (2002.10.22)
0.71 (2002.10.20)
0.70 (2002.10.17)
0.60 (2002.10.15)
0.60beta6 (2002.10.15)
0.52 (2002.10.10)
0.51 (2002.10.09)
0.50 (2002.10.03)