Class: Module

Inherits:
Object show all
Defined in:
lib/refining.rb

Instance Method Summary collapse

Instance Method Details

#refine_method(meth, options = {}, &block) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/refining.rb', line 54

def refine_method (meth, options = {}, &block)
  return unless block

  if options[:alias] || options[:prefix]
    instance_eval {
      begin
        alias_method options[:alias] || "#{options[:prefix]}_#{meth}", meth
      rescue NameError
        define_method options[:alias] || "#{options[:prefix]}_#{meth}" do |*args| end
      end

      define_method meth, &block
    }
  else
    (instance_method(meth) rescue nil).tap {|old|
      old ||= proc {}

      define_method meth do |*args, &blk|
        target = self
        what   = class << target
          self
        end

        what.instance_eval {
          define_method 'temporary method for refining', &block

          target.__send__('temporary method for refining', old.is_a?(UnboundMethod) ? old.bind(target) : old, *args, &blk).tap {
            undef_method 'temporary method for refining' rescue nil
          }
        }
      end
    }
  end
end