#--
# CREDIT Pit Captain (for delegation fix)
#++

require 'facets/more/functor'
require 'facets/core/module/basename'

class Module

  # Define a simple method namespace.
  #
  #   class A
  #     attr_writer :x
  #     namespace :inside do
  #       def x; @x; end
  #     end
  #   end
  #
  #   a = A.new
  #   a.x = 10
  #   a.inside.x #=> 10
  #   a.x  # no method error
  #

  def namespace( name, mod=nil, &blk )

    # If block is given then create a module, otherwise
    # get the name of the module.
    if block_given?
      name = name.to_s
      raise ArgumentError if mod
      mod  = Module.new(&blk)
    else
      if Module === name
        mod = name
        name = mod.basename.downcase
      end
      mod  = mod.dup
    end

    # Include the module. This is neccessary, otherwise
    # Ruby won't let us bind the instance methods.
    include mod

    # Save the instance methods of the module and
    # replace them with a "transparent" version.
    methods = {}
    mod.instance_methods(false).each do |m|
      methods[m.to_sym] = mod.instance_method(m)
      mod.instance_eval do
        define_method(m) do
          super
        end
      end
    end

    # Add a method for the namespace that delegates
    # via the Functor to the saved instance methods.
    define_method(name) do
      Functor.new(methods) do |op, mtab, *args|
        mtab[op].bind(self).call(*args)
      end
    end
  end

end


=begin test

  require 'test/unit'

  class TestNamespace1 < Test::Unit::TestCase

    module M
      def x; "x"; end
    end

    class C
      namespace M
    end

    def test_01
      c = C.new
      assert_equal('x', c.m.x)
    end

    def test_02
      c = C.new
      assert_raises(NoMethodError){ c.x }
    end

  end


  class TestNamespace2 < Test::Unit::TestCase

    class B
      def x; 1; end
    end

    class C < B
      def x; super; end
      namespace :m do
        def x; "x"; end
      end
    end

    def test_01
      c = C.new
      assert_equal('x', c.m.x)
    end

    def test_02
      c = C.new
      assert_equal(1, c.x)
    end

  end

=end

