Class: LazyObject

Inherits:
Object
  • Object
show all
Defined in:
lib/galleruby/utilities.rb

Overview

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.

Instance Method Summary collapse

Constructor Details

#initialize(&code) ⇒ LazyObject



20
21
22
# File 'lib/galleruby/utilities.rb', line 20

def initialize(&code)
    @init = code
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/galleruby/utilities.rb', line 28

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

Instance Method Details

#was_initialized?Boolean



24
25
26
# File 'lib/galleruby/utilities.rb', line 24

def was_initialized?
    not @object.nil?
end