Created
November 9, 2011 11:48
-
-
Save kerryb/1351214 to your computer and use it in GitHub Desktop.
dynamically including a module depending on an instance property
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 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