Created
February 27, 2011 06:19
-
-
Save jorgenpt/845956 to your computer and use it in GitHub Desktop.
Create on use
This file contains hidden or 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 to easily instantiate an object when needed. | |
# Similar to using (object ||= Foo.new).bar, but stores the initialization code to make | |
# the code cleaner. | |
class LazyObject | |
@object = nil | |
def initialize(&code) | |
@init = code | |
end | |
def was_initialized? | |
not @object.nil? | |
end | |
def method_missing(m, *args, &block) | |
if not was_initialized? then | |
@object = @init.call | |
@object.public_methods(false).each do |meth| | |
(class << self; self; end).class_eval do | |
define_method meth do |*args| | |
@object.send meth, *args | |
end | |
end | |
end | |
@object.send m, *args, &block | |
else | |
super.method_missing m, *args, &block | |
end | |
end | |
end | |
if __FILE__ == $0 then | |
# This is a bit of a forced use-case, LazyObject was created to reduce | |
# time spent creating unused, heavy-weight objects, e.g. RMagick's Image | |
# classes from file. | |
a = LazyObject.new { Array.new ["foo"] } | |
a << "bar" if rand >= 0.5 | |
if a.was_initialized? | |
puts a.inspect | |
else | |
puts "Did not initialize object!" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment