Skip to content

Instantly share code, notes, and snippets.

@floere
Forked from severin/lazy_proxy.rb
Created March 17, 2010 21:01
Show Gist options
  • Save floere/335716 to your computer and use it in GitHub Desktop.
Save floere/335716 to your computer and use it in GitHub Desktop.
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