简体   繁体   English

ruby类方法可以从另一个类继承吗?

[英]Can a ruby class method inherit from another class?

I read here that a ruby class can only inherit from one class, and can include modules. 在这里读到,ruby类只能从一个类继承,并且可以include模块。

However, the devise module defines controllers like this: 但是,devise模块定义了如下控制器:

class Users::PasswordsController < Devise::PasswordsController
  ...
end

Now, given that Users is probably a class, with PasswordsController being a method: 现在,假设Users可能是一个类,而PasswordsController是一个方法:

>> Devise::PasswordsController.class
=> Class

How is it that a method in a class inherits from another class? 一个类中的方法如何从另一个类继承?

class Users::PasswordsController < Devise::PasswordsController
...
end

In the above code, Users is the module and PasswordsController is the class inside Users module. 在上面的代码中,Users是模块,而PasswordsController是Users模块中的类。 Similarly Devise is the module and PasswordsController is the class inside Devise module. 同样,Devise是模块,而PasswordsController是Devise模块中的类。

so when you run 所以当你跑步

Users::PasswordsController.class
#=> Class
Users.class
#=>Module

What confuses you here is that you have wrong assumptions, namely: 令您感到困惑的是您有错误的假设,即:


Users is probably a class Users可能是一类

Not necessarily. 不必要。 Here we have namespace with nesting, therefore Users can be either a class or a module. 这里我们有嵌套的名称空间,因此Users可以是类或模块。 In fact classes are modules. 实际上,类模块。


PasswordsController being a method PasswordsController是一种方法

PasswordsController here is a class nested in the Users namespace. 这里的PasswordsController是嵌套在Users命名空间中的类。 :: simply lets you go one level into the nesting tree. ::仅使您可以进入嵌套树的一级。


Consider: 考虑:

module Foo
  class Bar
  end
end

Foo::Bar.class # => class

From Rails naming convention, Users is most probably a module, and Users::PasswordsController is a class. 根据Rails的命名约定, Users很可能是一个模块,而Users::PasswordsController是一个类。

Note that :: is not for calling class methods (although it can be used this way). 请注意, ::不是用于调用类方法的(尽管可以通过这种方式使用它)。 It's for accessing constants inside a module/class. 它用于访问模块/类中的常量。 For example 例如

module Foo
  BAR = 'bar'
end

Foo::BAR
#=> "bar"

In Ruby, a module/class name is a constant, and the value stored in it is the module/class. 在Ruby中,模块/类名是一个常量,存储在其中的值是模块/类。 So :: also is used for accessing a module/class inside another module/class. 因此, ::也用于访问另一个模块/类中的模块/类。 For example 例如

module Foo
  class Bar
  end
end

Foo::Bar
#=> Foo::Bar

“用户”和“设备”都是模块,仅用于确定真实的类,即PasswordsController和PasswordsController。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM