--- V1 ---
v1_titi
undefined method `to_v2' for "titi":String
--- V2 ---
v2_titi
undefined method `to_v1' for "titi":String
Last active
August 29, 2015 14:07
-
-
Save mdouchement/77bc4b16e51500b1b737 to your computer and use it in GitHub Desktop.
Selective instance eval
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
String.class_eval do | |
alias_method :original_initialize, :initialize | |
def initialize(*args) | |
# https://www.ruby-forum.com/topic/1893190 | |
c = caller(0) | |
case | |
when c.to_s.include?('module:V1') | |
instance_eval do | |
def to_v1 | |
"v1_#{self}" | |
end | |
end | |
when c.to_s.include?('module:V2') | |
instance_eval do | |
def to_v2 | |
"v2_#{self}" | |
end | |
end | |
end | |
original_initialize(*args) | |
end | |
end | |
puts '--- V1 ---' | |
module V1 | |
puts String.new('titi').to_v1 | |
puts String.new('titi').to_v2 | |
rescue => ex | |
puts ex.message | |
end | |
puts '--- V2 ---' | |
module V2 | |
puts String.new('titi').to_v2 | |
puts String.new('titi').to_v1 | |
rescue => ex | |
puts ex.message | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment