Module: ProxyModule

Defined in:
lib/proxy_module.rb,
lib/proxy_module/version.rb

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.__add_method_added(_base, imod, smod, handler, opts) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/proxy_module.rb', line 44

def self.__add_method_added(_base, imod, smod, handler, opts)
  smod.module_eval do
    define_method :method_added do |imethod|
      return if imod.method_defined?(imethod) && imod.instance_method(imethod).owner == imod

      ProxyModule.__add_proxy_method(imod, imethod, handler, opts)

      super(imethod)
    end

    define_method :singleton_method_added do |smethod|
      return if smod.method_defined?(smethod) && smod.instance_method(smethod).owner == smod

      ProxyModule.__add_proxy_method(smod, smethod, handler, opts)

      super(smethod)
    end
  end
end

.__add_proxy_method(context, method_name, handler, opts) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/proxy_module.rb', line 25

def self.__add_proxy_method(context, method_name, handler, opts)
  return if opts[:only] && !opts[:only].include?(method_name)
  return if opts[:except] && opts[:except].include?(method_name)

  context.class_eval do
    define_method method_name do |*args, &block|
      handler.call(self, method_name, args, block, proc { |args2, block2| super *args2, &block2 })
    end
  end
end

.__for(base, handler, opts) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/proxy_module.rb', line 36

def self.__for(base, handler, opts)
  Module.new do
    base.instance_methods.each do |imethod|
      ProxyModule.__add_proxy_method(self, imethod, handler, opts)
    end
  end
end

.for(base, opts = {}, &handler) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/proxy_module.rb', line 4

def self.for(base, opts = {}, &handler)
  imod = __for(base, handler, opts)
  smod = __for(base.singleton_class, handler, opts)
  __add_method_added(base, imod, smod, handler, opts)

  Module.new do
    define_singleton_method :prepend_features do |base|
      base.prepend(imod)
      base.singleton_class.prepend(smod)
    end

    define_singleton_method :imod do
      imod
    end

    define_singleton_method :smod do
      smod
    end
  end
end