namespace.rb

Ruby code posted by zimbatm
created at 04 Dec 12:41

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Module
  # BasicObject is used to limit the size of the exposed interface
  class Instance < BasicObject
    def initialize(mod, &fixes)
      # BasicObject doesn't expose #extend and #singleton_class
      (class << self; self; end).instance_eval do
        include(mod)
        instance_eval(&fixes) if block_given?
      end
    end
  end

  module Namespace
    # Exposes a module +mod+ under a given +name+.
    #
    # +fixes+ is executed under the context of the exposed module and useful
    # for tweaking the visibility of old modules.
    def import(name, mod, &fixes)
      instance = Instance.new(mod, &fixes)
      define_method(name) { instance }
      protected(name)
    end
  end

  include Namespace
end

if __FILE__ == $0
  module ExampleNamespace
    def foo; "foo"; end
  end

  class Bar
    import "ex", ExampleNamespace
    import "math", Math do
      public :sqrt
    end

    def is_it_working?
      ex.foo == "foo" && math.sqrt(4) == 2.0
    end
  end

  b = Bar.new
  p [:working?, b.is_it_working?]
end
1.06 KB in 5 ms with coderay