Skip to content

Instantly share code, notes, and snippets.

@simonbaird
Created February 24, 2011 05:29
Show Gist options
  • Save simonbaird/841810 to your computer and use it in GitHub Desktop.
Save simonbaird/841810 to your computer and use it in GitHub Desktop.
test including a module on the fly using the singleton class (probably a bad idea...)
# Where the magic happens...
module RuntimeInclude
def get_singleton
class << self
self
end
end
def runtime_include(the_module)
get_singleton.send(:include,the_module)
end
end
module Payments
module DPS
def foo
"dps"
end
end
module EWAY
def foo
"eway"
end
end
end
class Booking
include RuntimeInclude
def lets_go_eway
runtime_include(Payments::EWAY)
end
def lets_go_dps
runtime_include(Payments::DPS)
end
def foo
"none"
end
end
booking1 = Booking.new
puts "booking1 (original): #{booking1.foo}"
booking1.lets_go_eway
puts "booking1 (eway): #{booking1.foo}"
booking2 = Booking.new
booking2.lets_go_dps
puts "booking2 (dps): #{booking2.foo}"
puts "booking1 (still eway): #{booking1.foo}"
# You can flip it but only once. Scary..?
# I'm guessing once a module is included, re-including it does nothing
booking1.lets_go_dps
puts "booking1 (now dps): #{booking1.foo}"
booking1.lets_go_eway
puts "booking1 (is still dps): #{booking1.foo}"
# output:
# booking1 (original): none
# booking1 (eway): eway
# booking2 (dps): dps
# booking1 (still eway): eway
# booking1 (now dps): dps
# booking1 (is still dps): dps
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment