Skip to content

Instantly share code, notes, and snippets.

@skwp
Created August 24, 2009 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skwp/173952 to your computer and use it in GitHub Desktop.
Save skwp/173952 to your computer and use it in GitHub Desktop.
Lazy decorator pattern for ruby
# Creates the ability to lazily initialize
# a class. This means the instance will not
# be created until a method is called on it.
# Useful for objects that create connections or
# use other expensive resources.
#
# example:
#
# class ExpensiveObject
# def initialize
# @conn = Connection.new # this is really expensive
# end
#
# def make_a_call
# @conn.foo!
# end
# end
#
# usage:
# foo = LazyDecorator.new { ExpensiveObject.new } # note, at this point the connction has not yet been created
# foo.make_a_call # now the connection gets created
#
class LazyDecorator
def initialize(&block)
@init_block = block
end
def method_missing(sym, *args, &block)
@instance ||= @init_block.call
@instance.send sym, *args, &block
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment