Skip to content

Instantly share code, notes, and snippets.

@pasberth
Created December 12, 2011 15:35
Show Gist options
  • Select an option

  • Save pasberth/1467896 to your computer and use it in GitHub Desktop.

Select an option

Save pasberth/1467896 to your computer and use it in GitHub Desktop.
べつのクラスを一時的に同じインスタンスのように振る舞わせる
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