简体   繁体   中英

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.

However, the devise module defines controllers like this:

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

Now, given that Users is probably a class, with PasswordsController being a method:

>> 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. Similarly Devise is the module and PasswordsController is the class inside Devise module.

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

Not necessarily. Here we have namespace with nesting, therefore Users can be either a class or a module. In fact classes are modules.


PasswordsController being a method

PasswordsController here is a class nested in the Users namespace. :: 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.

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. 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。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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