Skip to content

Instantly share code, notes, and snippets.

@jorgenpt
Created February 27, 2011 06:19
Show Gist options
  • Save jorgenpt/845956 to your computer and use it in GitHub Desktop.
Save jorgenpt/845956 to your computer and use it in GitHub Desktop.
Create on use
# 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