use*_*870 58 ruby activerecord ruby-on-rails
据我所知,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
Run Code Online (Sandbox Code Playgroud)
此代码来自rails master分支.非常感谢.
mač*_*ček 45
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
Run Code Online (Sandbox Code Playgroud)
puts Car.ancestors.inspect
# Output
# [Car, Vehicle, Vehicular, Object, Kernel, BasicObject]
Run Code Online (Sandbox Code Playgroud)
注意包含Vehicular
Module
对象!
Gis*_*shu 15
检查objRef.class.ancestors
或ClassName.ancestors
了解继承链.如果超类不包含该方法,则检查超类包含的所有模块(最后包括先检查).如果没有匹配,则它向上移动一级到祖父级,依此类推.
您可以使用祖先列表,然后AncestorClass.methods.select{|m| m.include?("auto_load")}
在被调用的方法上调用zone.
(注意:上面的代码是Ruby 1.8.在1.9中methods
返回符号而不是字符串.所以你必须做一个m.to_s.include?(...
)
hor*_*guy 14
使用Pry
binding.pry
在使用之前插入一个调用super
,然后调用show-source -s
(-s
means 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>
Run Code Online (Sandbox Code Playgroud)
该super
关键字检查一路祖先树找到继承的方法.
在整个rails master分支上搜索.你只能找到一个def autoload
正是你正在看的那个active_support/lib/active_support/dependencies/autoload.rb
.
被覆盖的方法是原生Ruby.它是Module#autoload
归档时间: |
|
查看次数: |
67896 次 |
最近记录: |