ProgramingTip

루비 슈퍼 키워드

bestdevel 2020. 12. 25. 10:28
반응형

루비 슈퍼 키워드


내가 이해하는 바에 따르면 super키워드는 현재 클래스의 수퍼 클래스에서 현재 메소드와 동일한 이름을 가진 메소드를 호출합니다. autoload메서드 아래 에는 super. 동일한 이름의 메서드를 사용 하는 수퍼 클래스 또는 super여기 에서 수행 하는 호출이 무엇인지 알고 싶습니다.

module ActiveSupport
  module Autoload
    ...      
    def autoload(const_name, path = @@at_path)
      full = [self.name, @@under_path, const_name.to_s, path].compact.join("::")
      location = path || Inflector.underscore(full)

      if @@eager_autoload
        @@autoloads[const_name] = location
      end
      super const_name, location
    end
   .... 
  end
end

module ActiveRecord
  extend ActiveSupport::Autoload
  ...
  autoload :TestCase
  autoload :TestFixtures, 'active_record/fixtures'
end

이 코드는 레일스 마스터 브랜치에서 레일스 마스터입니다. 고맙습니다.


Ruby 문서에서 super키워드에 대해 예시 :

module Vehicular
  def move_forward(n)
    @position += n
  end
end

class Vehicle
  include Vehicular  # Adds Vehicular to the lookup path
end

class Car < Vehicle
  def move_forward(n)
    puts "Vrooom!"
    super            # Calls Vehicular#move_forward
  end
end

조상 검사

puts Car.ancestors.inspect

# Output
# [Car, Vehicle, Vehicular, Object, Kernel, BasicObject]

Vehicular Module개체 포함 에 유의하십시오 !


상속 체인을 확인 objRef.class.ancestors하거나 ClassName.ancestors알고 있습니다. 수퍼 클래스에 메소드가 포함되지 않은 경우 수퍼 클래스에 포함 된 모든 모듈이 검사됩니다 (마지막 포함 된 모듈이 먼저 검사 됨). 일치하지 않는 조직 조부모 클래스로 한 단계 위로 이동합니다.
조상 목록을 사용할 다음 호출 AncestorClass.methods.select{|m| m.include?("auto_load")}되는 메서드에서 영역 을 호출 할 수 있습니다 .

(참고 : 위의 코드는 Ruby 1.8입니다. 1.9에서는 methods대신 기호를 사용하여 수행해야합니다. m.to_s.include?(...)


들어 올립니다 사용

binding.pry를 사용하기 직전 호출을 삽입 한 super다음 show-source -s( -smeans superclass)를 호출 하여 수퍼 클래스 메서드를 표시하고 정의 된 위치를 찾습니다.

class A
  def hello
    puts "hi"
  end
end

class B < A
  def hello
    binding.pry
    super
  end
end

b = B.new
b.hello

From: (pry) @ line 7 B#hello:

     7: def hello
 =>  8:   binding.pry
     9:   super
    10: end

[1] (pry) #<B>: 0> show-source -s

From: (pry) @ line 2:
Number of lines: 3
Owner: A   # <--see owner here (i.e superclass)
Visibility: public

def hello
  puts "hi"
end
[2] (pry) #<B>: 0>    

super키워드는 상속 된 메서드를 찾기 위해 조상 트리를 끝까지 확인합니다.

레일스 마스터 브랜치 전체를 검색하십시오. def autoload에서보고있는 것과 정확히 일치하는 것만 찾을 수 있습니다 active_support/lib/active_support/dependencies/autoload.rb.

재정의되는 메서드는 기본 Ruby입니다. 그것은Module#autoload


내 .irbrc에 메서드의 소유자를 찾기 위해이 메서드를 추가했습니다. 특히 싱글 톤 클래스의 슈퍼 클래스가 슈퍼 클래스의 싱글 톤 클래스 인 싱글 톤 메서드를 처리 할 때 더 나은 방법을 볼 수 있습니까?

  class Object
    def find_method(method_string)
        if klasses = self.class.ancestors.select { |a| a if a.methods.include? method_string }
          puts "class method in #{klasses.join(',')}" unless klasses.empty?
        end
        if klasses = self.class.ancestors.select { |a| a if a.instance_methods.include? method_string }
          puts "instance method in #{klasses.join(',')}" unless klasses.empty?
        end
      rescue
        raise "owning class not found"
    end
  end

관련 수퍼 클래스 메소드는 아마도 Module # autoload 입니다.

참조 URL : https://stackoverflow.com/questions/2597643/ruby-super-keyword

반응형