>>>>> "T" == Tomasz Wegrzanowski <taw / users.sourceforge.net> writes:

T> So user program calls Foo::Bar.new
T> Foo::Bar isn't registered yet. So Ruby calls some function in Foo,
T> which sees that "Bar" is being requested. It checks in it's database
T> what bar ought to be, creates it, and calls Foo::Bar.new, which
T> returns new object. Next time when Foo::Bar is called it already
T> exists, so nothing extraordinary needs to happen.

 Except, I think, that ruby don't work like this :-)

 When you write  Foo::Bar, ruby first search for the constant Foo if it
 don't find it it give an error. If Foo is a class or a module, then ruby
 search the constant Foo::Bar or it give an error, otherwise it try to call
 the method Foo::Bar()

 What you can do is rather than call Foo::Bar.new() call Foo.Bar() which
 (via #method_missing) will create the class Foo::Bar (if it don't exist)
 and then call the method ::new (something like Kernel#Integer)

 Something like this

pigeon% cat b.rb
#!/usr/bin/ruby
module Foo
   def self.method_missing(arg)
      bar = if const_defined?(arg)
               puts "retrieve #{arg}"
               const_get(arg)
            else
               puts "create   #{arg}"
               const_set(arg, Class.new)
            end
      bar.new
   end
end

p Foo.Bar()
p Foo.Bar()
pigeon% 

pigeon% b.rb
create   Bar
#<Foo::Bar:0x401b06f8>
retrieve Bar
#<Foo::Bar:0x401b0518>
pigeon% 



Guy Decoux