Class: Utter::Utils::Wrapper

Inherits:
Object
  • Object
show all
Defined in:
lib/utter/utils/wrapper.rb

Instance Method Summary collapse

Instance Method Details

#wrap(wrapped_class, before: nil, after: nil) ⇒ Object



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
# File 'lib/utter/utils/wrapper.rb', line 4

def wrap(wrapped_class, before: nil, after: nil)
  wrapped_class.class_eval do
    self.define_singleton_method :utter_before_action do
      before || Proc.new {}
    end

    self.define_singleton_method :utter_after_action do
      after || Proc.new {}
    end

    def self.inherited(klass)
      def klass.method_added(name)
        # prevent a SystemStackError
        return if @_not_new
        @_not_new = true

        # preserve the original method call
        original = "original #{name}"
        alias_method original, name

        # wrap the method call
        define_method(name) do |*args, &block|
          self.class.superclass.utter_before_action.call(self, args, name)

          # call the original method
          result = send original, *args, &block

          self.class.superclass.utter_after_action.call(self, args, name)

          # return the original return value
          result
        end

        # reset the guard for the next method definition
        @_not_new = false
      end
    end
  end
end