
require 'delegate'

class Module

  # Create a seperated method namespace.
  #
  #   module T
  #     def t ; "HERE" ; end
  #   end
  #
  #   class X
  #     namespace :test { include T }
  #     def t ; test.t ; end
  #   end
  #
  #   X.new.t  #=> "HERE"
  #
  # NOTE: This is not as functional as it ought be in that
  # the instance variables of the object are not accessible
  # within the namespace.

  def namespace( name, &blk )
    s = self
    c = Class.new(SimpleDelegator, &blk)
    c.class_eval { define_method(:initialize) { |s| super(s) } }
    self.class_eval {
      define_method( name ) {
        instance_variable_set( "@#{name}",  instance_variable_get("@#{name}") || c.new(s) )
      }
    }
  end

end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCModule < Test::Unit::TestCase

    class MockObject
      namespace(:hope) {
        def watch ; 'watch' ; end
      }
    end

    def test_namespace
      m = MockObject.new
      assert_equal( 'watch', m.hope.watch )
    end

  end

=end
