Skip to content

Instantly share code, notes, and snippets.

@mdouchement
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdouchement/77bc4b16e51500b1b737 to your computer and use it in GitHub Desktop.
Save mdouchement/77bc4b16e51500b1b737 to your computer and use it in GitHub Desktop.
Selective instance eval
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
--- V1 ---
v1_titi
undefined method `to_v2' for "titi":String
--- V2 ---
v2_titi
undefined method `to_v1' for "titi":String
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment