Created
August 17, 2008 23:28
-
-
Save auser/5867 to your computer and use it in GitHub Desktop.
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 MethodMissingSuga | |
def method_missing(m, *args, &block) | |
args[0].instance_eval(&block) if block | |
args.empty? ? options[m] : options[m] = args[0] | |
end | |
def options | |
@options ||= {} | |
end | |
def initialize(&block) | |
self.instance_eval(&block) if block | |
end | |
end | |
class Doc | |
include MethodMissingSuga | |
end | |
class Goose | |
include MethodMissingSuga | |
end | |
class Red | |
include MethodMissingSuga | |
end | |
d = Doc.new do | |
hi "you" | |
mydoc Goose.new do | |
who 'me' | |
yes Red.new do | |
you "you" | |
end | |
no 1 | |
end | |
end | |
# When instance evaluating within the d Doc, hi is sent "you" as args | |
# but inside the block, mydoc's who is NOT sent "me." Instead, it is | |
# sent nil | |
puts d.hi # => you | |
puts d.mydoc # => #<Doc:0x338308> | |
puts d.mydoc.who # => me | |
puts d.mydoc.yes # => #<Doc:0x337f5c> | |
puts d.mydoc.yes.you # => you | |
puts d.mydoc.no # => a, b, c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment