-
-
Save floere/335716 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
class LazyProxy | |
instance_methods.each do |method| | |
undef_method(method) if method !~ /^__/ | |
end | |
def initialize &lazy_proxy_block | |
@lazy_proxy_block = lazy_proxy_block | |
end | |
def method_missing(method, *args, &block) | |
@lazy_proxy_obj ||= @lazy_proxy_block.call # evaluate the real receiver | |
@lazy_proxy_obj.send(method, *args, &block) # delegate unknown methods to the real receiver | |
end | |
end | |
module Kernel | |
def lazily &block | |
LazyProxy.new &block | |
end | |
end | |
couch_potato = lazily { lazily { lazily { [1,2,4,8] } } } | |
p couch_potato.inject(0) { |total, i| total + i } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment