Insert code into the beginning of each method of a

2019-09-22 03:43发布

问题:

How can I dynamically and easily insert code into the beginning of each method of a class and subclasses without actually inserting it manually? I want something like a macros.

class C1
   def m1
     @i_am = __method__
   end

   def m2
      @i_am = __method__
   end
 end

This is one of the examples where I want to avoid repetition.

回答1:

I initially misinterpreted the question (but have left my original answer after the horizontal line below). I believe the following may be what you are looking for.

class C1
  [:m1, :m2].each do |m|
    define_method(m) do |name|
      @i_am = __method__
      puts "I'm #{name} from method #{@i_am}"
    end
  end
end

C1.instance_methods(false)
  #=> [:m1, :m2] 
c1 = C1.new
  #=> #<C1:0x007f94a10c0b60> 
c1.m1 "Bob"
  # I'm Bob from method m1
c1.m2 "Lucy"
  # I'm Lucy from method m2

My original solution follows.

class C1
  def add_code_to_beginning(meth)
    meth = meth.to_sym
    self.class.send(:alias_method, "old_#{meth}".to_sym, meth)
    self.class.send(:define_method, meth) do
      yield
      send("old_#{meth}".to_sym)
    end
  end
end

Module#alias_method and Module#define_method are private; hence the need to use send.

c = C1.new
  #=> #<C1:0x007ff5e3023650> 
C1.instance_methods(false)
  #=> [:m1, :m2, :add_code_to_beginning] 

c.add_code_to_beginning(:m1) do
  puts "hiya"
end

C1.instance_methods(false)
  #=> [:m1, :m2, :add_code_to_beginning, :old_m1] 
c.m1
  # hiya
  #=> :m1 


回答2:

You can use a rails like class decorators to that. The piece of code below is rendering a method called before_action defined in the Base class of the ActiveRecord module. The Test class is inherited from the ActiveRecord. The define_method is used if we want to call something explicitly from the Base class.

module ActiveRecord
    class Base

        def self.before_action(name)
            puts "#{name}"
            puts "inside before_action of class Base"

            define_method(name) do
                puts "Base: rendering code from Base class"
            end
        end
    end
end

class Test < ActiveRecord::Base

    before_action :hola

    def render()
        puts "inside render of class Test"
    end

end

test = Test.new
test.render
test.hola

It has the output

hola
inside before_action of class Base
inside render of class Test
Base: rendering code from Base class

So, before running the render method it runs the before_action method in the Base class. It can be applied to all other methods in the Test class. This is a way of representing macros in ruby.



回答3:

Assuming that the function is the same, you could create a module and include it in your classes.

Example:

module MyModule
  def test_method
    puts "abc"
  end
end

class MyClass
  include MyModule
  def my_method
    puts "my method"
  end
end

inst = MyClass.new
inst.test_method # => should print "abc"
inst.my_method   # => should print "my method"