method_missing override is not working

后端 未结 1 925
小蘑菇
小蘑菇 2021-01-19 10:15

I wrote a convenience ActiveRecord extension to delegate methods to a base object (based on multi-table inheritance)

class ActiveRecord::Base
  def self.acts_as(b         


        
1条回答
  •  有刺的猬
    2021-01-19 11:08

    When you run MyObject.first.tail the object that actually responds is an AssociationProxy class that

    has most of the basic instance methods removed, and delegates # unknown methods to @target via method_missing

    You can get more details about the proxy running:

    MyObject.first.proxy_owner
    MyObject.first.proxy_reflection
    MyObject.first.proxy_target
    

    If you look in the code, you can see that the AssociationProxy proxies the method some_method_in_base to your MyState class only if MyState responds to some_method_in_base as you can see in the code below.

      private
        # Forwards any missing method call to the \target.
        def method_missing(method, *args, &block)
          if load_target
            if @target.respond_to?(method)
              @target.send(method, *args, &block)
            else
              super
            end
          end
        end
    

    Therefore, the method_missing you have defined in the target class is never called.

    0 讨论(0)
提交回复
热议问题