Is it possible to run code after each line in Ruby?

前端 未结 3 812
攒了一身酷
攒了一身酷 2020-12-19 16:56

I understand that it is possible to decorate methods with before and after hooks in ruby, but is it possible to do it for each line of a given method?

For example, I

3条回答
  •  Happy的楠姐
    2020-12-19 17:11

    What about (just tries)

        class User
    
          def initialize(name)
            @name = name
          end
    
          def say_hello
            puts "hello #{@name}"
          end
    
          def say_hi(friend)
            puts "hi #{@name} from #{friend}"
          end
    
          def say_bye(a, b = 'Anna')
            puts "bye #{a} and #{b}"
          end
    
        end
    
        User.class_eval do
          User.instance_methods(false).each do |method|
            original = instance_method(method)
            define_method method do |*options| 
              parameters = original.parameters
              if parameters.empty?
                original.bind(self).call
              else
                original.bind(self).call(*options)
              end
              puts __method__
            end
          end
        end
    
        user = User.new("John")
    
        user.say_hello
        user.say_hi("Bob")
        user.say_bye("Bob")
        user.say_bye("Bob", "Lisa")
    

    outputs:

        hello John
        say_hello
        hi John from Bob
        say_hi
        bye Bob and Anna
        say_bye
        bye Bob and Lisa
        say_bye
    

提交回复
热议问题