Created
December 12, 2011 15:35
-
-
Save pasberth/1467896 to your computer and use it in GitHub Desktop.
べつのクラスを一時的に同じインスタンスのように振る舞わせる
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Object | |
| alias checkout_original_method_missing method_missing | |
| def checkout! into | |
| into = case into.class | |
| when Class then into.new | |
| when Module then Object.new.tap { |i| i.extend into } | |
| else into end | |
| define_singleton_method :method_missing do |f, *a, &b| | |
| begin | |
| checkout_original_method_missing f, *a, &b | |
| rescue NoMethodError => e | |
| into.send f, *a, &b | |
| end | |
| end | |
| end | |
| def checkout into | |
| clone.checkout! into | |
| end | |
| end | |
| class A < Array | |
| def hello; "hello"; end | |
| end | |
| o = Array.new | |
| o.checkout! A | |
| puts o.hello # hello |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment