how rails delegate method works?

后端 未结 2 750
死守一世寂寞
死守一世寂寞 2021-02-05 12:50

After reading the answer by jvans below and looking at the source code a few more time I get it now :). And in case anyone is still wondering how exactly rails delegates works.

2条回答
  •  迷失自我
    2021-02-05 13:24

    After reading the answer by jvans below and looking at the source code a few more time I get it now :). And in case anyone is still wondering how exactly rails delegates works. All rails is doing is creating a new method with (module_eval) in the file/class that you ran the delegate method from.

    So for example:

      class A
        delegate :hello, :to => :b
      end
    
      class B
        def hello
         p hello
        end
      end
    

    At the point when delegate is called rails will create a hello method with (*args, &block) in class A (technically in the file that class A is written in) and in that method all rails do is uses the ":to" value(which should be an object or a Class that is already defined within the class A) and assign it to a local variable _, then just calls the method on that object or Class passing in the params.

    So in order for delegate to work without raising an exception... with our previous example. An instance of A must already have a instance variable referencing to an instance of class B.

      class A
        attr_accessor :b
    
        def b
          @b ||= B.new
        end
    
        delegate :hello, :to => :b
      end
    
      class B
        def hello
         p hello
        end
      end
    

提交回复
热议问题