Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
dynamically including a module depending on an instance property
module DynamicSetup
def dynamic_setup_complete?
@dynamic_setup_complete
end
def method_missing name, *args, &block
if dynamic_setup_complete?
super
else
perform_dynamic_setup
@dynamic_setup_complete = true
send name, *args, &block
end
end
end
class Foo
include DynamicSetup
module Normal
def greeting
"Hello"
end
end
module Silly
def greeting
"Wibble"
end
end
def initialize silly = false
@silly = silly
end
def perform_dynamic_setup
extend @silly ? Silly : Normal
end
end
puts Foo.new.greeting # => "Hello"
puts Foo.new(true).greeting # => "Wibble"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment