在模块中定义类方法 [英] Define a class method in a module

查看:52
本文介绍了在模块中定义类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是,我想在我的模块中创建一个类方法,该方法将由包含该模块的类使用.它们位于单独的文件中.

I mean, I want to create a class method in my module that will be used by the class who includes the module. They are in separated files.

到目前为止,我有这样的事情:

By far I have something like this:

module Base
  def self.all
    puts "All Users"
  end
end

class User
  include Base
end

但我得到:NoMethodError: undefined methodall' for User:Class`

But I'm getting: NoMethodError: undefined methodall' for User:Class`

你能解释一下这个问题吗?我的做法是不好的做法还是违反任何原则?

Can you please explain the problem and if what I'm doing is a bad practice or going against any principle?

推荐答案

你可以extend你的类中的模块,你的代码应该是这样的:

You can extend the module in your class, your code should be like this:

module Base
  def all
    puts "All Users"
  end
end

class User
  extend Base
end

当你做这样的事情时:

module MyModule
  def self.module_method
    puts "module!"
  end
end

您实际上是在模块本身中添加方法,您可以像这样调用前面的方法:

You're actually adding the method in the module itself, you could call the previous method like this:

MyModule.module_method

有一种方法可以只包含 module 并获得您想要的行为,但我认为这不能被视为要走的路".看例子:

There is a way to just include the module and get the behaviour that you want, but I don't think this could be considered the "way to go". Look at the example:

module Base
  def self.included(klass)
    def klass.all
      puts "all users"
    end
  end
end

class User
  include Base
end

但就像我说的,如果你可以使用 extend 类方法,那就更合适了.

But like I said, if you can go with the extend class method, it is a better suit.

这篇关于在模块中定义类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆