新手问题 [已解决] module 中的 class 继承很有意思

xiaoronglv · 2014年06月28日 · 最后由 sefier 回复于 2014年07月02日 · 2890 次阅读

module 中的继承

class A
  def self.a 
    p "I am root A"
  end
end


module M
  class A
    def self.a
     p "I am A with namespace"
    end
  end
end


module M
  # B 先去找找  M::A 这个 class
  # 找不到的话,就去找 ::A 这个 class
  class B < A
  end
end

M::B.a "I am A with namespace"

M::B.superclass => M::A

如果在 module 下找不到 M::A,B 会一层一层的往上扒

class A
  def self.a 
    p "I am root A"
  end
end


module M
  class B < A
  end
end

M::B.a "I am root A"

M::B.superclass => A

我后知后觉,今天才认真思考这个问题,嘎嘎。

Ruby 为什么这么随意啊?

为什么不要求写代码的人明确指定父类?

Rails 的查询机制更神奇

> Api::ApplicationController
ApplicationController

自动把 namespace 下一个不存在的类Api::ApplicationController指向:: ApplicationController

Ruby class 和 module 名是常量,所以当 M::A 这个常量找不到时,就一层层向外层寻找

一年前发过一个贴 Ruby 的常量查找路径问题 https://ruby-china.org/topics/4777 对 Ruby 常量查找路径问题讲得最清楚的一篇文章 Everything you ever wanted to know about constant lookup in Ruby http://cirw.in/blog/constant-lookup

这个跟继承毫无关系

需要 登录 后方可回复, 如果你还没有账号请 注册新账号