Sha256: 7fbd36629918afd0f95823ca08722ea5a9c99e871050532244e0578f26f3c94f

Contents?: true

Size: 1.37 KB

Versions: 20

Compression:

Stored size: 1.37 KB

Contents

require 'delegate'

class Module

  # Include a module via a specified namespace.
  #
  #   module T
  #     def t ; "HERE" ; end
  #   end
  #
  #   class X
  #     include_as :test => T
  #     def t ; test.t ; end
  #   end
  #
  #   X.new.t  #=> "HERE"
  #
  def include_as( h )
    h.each{ |name, mod|
      s = self
      c = Class.new(SimpleDelegator) {
        include mod
        define_method(:initialize) { |s| super(s) }
      }
      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

    module MockModule
      def mm; 77; end
    end

    class MockObject
      include_as :mod => MockModule
    end

    def test_include_as
      m = MockObject.new
      assert_equal( 77, m.mod.mm )
    end

  end

=end


# devlopment testing

=begin

if __FILE__ == $0

  # test

  module T
    def t ; p self ; end
    def r ; p self ; end
    def q ; super ; end
  end

  class N
    def q ; puts "ho" ; end
  end

  class X < N
    include_as :test => T

    def n ; p test ; end
    def m ; test.t ; end
    def o ; test.r ; end
  end

  x = X.new
  x.n
  x.m
  x.o
  x.q

end

=end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
facets-1.0.3 packages/core/lib/facet/module/include_as.rb
facets-0.9.0 lib/nano/module/include_as.rb
facets-1.0.0 lib/facet/module/include_as.rb
facets-1.3.0 lib/facets/core/module/include_as.rb
facets-1.1.0 lib/facet/module/include_as.rb
facets-1.2.0 lib/facets/core/module/include_as.rb
facets-1.2.1 lib/facets/core/module/include_as.rb
facets-1.3.2 lib/facets/core/module/include_as.rb
facets-1.3.1 lib/facets/core/module/include_as.rb
facets-1.3.3 lib/facets/core/module/include_as.rb
facets-1.4.2 lib/facets/core/module/include_as.rb
facets-1.4.0 lib/facets/core/module/include_as.rb
facets-1.4.1 lib/facets/core/module/include_as.rb
facets-1.4.3 lib/facets/core/module/include_as.rb
facets-1.4.4 lib/facets/core/module/include_as.rb
facets-1.4.5 lib/facets/core/module/include_as.rb
facets-1.7.0 lib/facets/core/module/include_as.rb
facets-1.7.30 lib/facets/core/module/include_as.rb
facets-1.7.38 lib/facets/core/module/include_as.rb
facets-1.7.46 lib/facets/core/module/include_as.rb