Created
August 24, 2009 16:22
-
-
Save skwp/173952 to your computer and use it in GitHub Desktop.
Lazy decorator pattern for ruby
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
# 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