Created
May 19, 2012 10:17
-
-
Save melborne/2730356 to your computer and use it in GitHub Desktop.
replace superclass temporally in Ruby
This file contains 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
require './surrogate_dad' | |
# your real | |
class PoorDad | |
private | |
def money | |
100000 | |
end | |
end | |
class Me < PoorDad | |
def give_me_money | |
money * 0.01 | |
end | |
end | |
Me.new.give_me_money # => 1000.0 | |
# Masashi's real | |
class RichDad | |
private | |
def money | |
100000 * FaceBook.stock_value | |
end | |
end | |
class FaceBook | |
def self.stock_value | |
38 | |
end | |
end | |
class Masashi < RichDad | |
def give_me_money | |
money * 0.01 | |
end | |
end | |
Masashi.new.give_me_money # => 38000.0 | |
# now, Masashi's father becomes yours temporally! | |
include SurrogateDad | |
surrogate(Me, RichDad) do | |
Me.superclass # => RichDad | |
Me.class_eval do | |
def give_me_money | |
money * 0.01 | |
end | |
end | |
Me.new.give_me_money # => 38000.0 | |
end | |
Me.new.give_me_money # => 1000.0 |
This file contains 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
module SurrogateDad | |
def surrogate(klass, new_dad) | |
class_name = :"#{klass}" | |
real_class_name = :"Real#{klass}" | |
self.class.class_eval do | |
const_set(real_class_name, klass) | |
remove_const(class_name) | |
c = Class.new(new_dad) | |
const_set(class_name, c) | |
end | |
yield | |
ensure | |
self.class.class_eval do | |
remove_const(class_name) | |
const_set(class_name, const_get(real_class_name)) | |
remove_const(real_class_name) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment