How can a nested class access a method in the outer class in Ruby?

后端 未结 7 2028
-上瘾入骨i
-上瘾入骨i 2021-02-12 13:58
def class A
  def a
    raise \"hi\" #can\'t be reached
  end

  class B
    def b
      a() #doesn\'t find method a.
    end
  end
end

I want to invok

7条回答
  •  粉色の甜心
    2021-02-12 14:26

    Well depending on your circumstances there is actually a solution, a pretty easy one at that. Ruby allows the catching of method calls that aren't captured by the object. So for your example you could do:

    def class A
      def a
        raise "hi" #can't be reached
      end
    
      class B
        def initialize()
          @parent = A.new
        end
    
        def b
          a() #does find method a.
        end
    
        def method_missing(*args)
          if @parent.respond_to?(method)
            @parent.send(*args)
          else
            super
          end
        end
      end
    end
    

    So then if you do this:

    A::B.new().b
    

    you get:

    !! #
    

    It is probably an easier way to make something like a SubController that only handles certain activities, but can easily call basic controller methods (You would want to send in the parent controller as an argument in the initializer though).

    Obviously this should be used sparingly, and it can really get confusing if you use it all over the place, but it can be really great to simplify your code.

提交回复
热议问题