Ruby:调用模块中的类方法

时间:2021-05-10 23:20:57

I have a module, whose purpose is to act on any given ActiveRecord instance.

我有一个模块,其目的是对任何给定的ActiveRecord实例执行操作。

For argument's sake, let's say that this method puts the string "match" if it matches certain properties with another instance of the same type.

为了论证,让我们假设这个方法将字符串“匹配”,如果它将某些属性与另一个相同类型的实例匹配。

module Foo
  def check_against_other_instances
    self.all.each do |instance|
      if self.respond_to? :color && self.color == instance.color
        puts "match"
      end
    end
  end
end

However, I can't just simply call self.all here, because self is an instance. How do I call the class method all from here?

但是,我不能简单地在这里调用self.all,因为self是一个实例。如何从这里调用类方法?

3 个解决方案

#1


3  

Ah.. found the solution almost right after I asked...

啊..我问了几乎就找到了解决方案......

self.class.all.each do |instance| ...

self.class.all.each do | instance | ...

#2


0  

if you want to extend the behavior of rails classes, then you are best of using ActiveSupport::Concern!

如果你想扩展rails类的行为,那么你最好使用ActiveSupport :: Concern!

http://apidock.com/rails/ActiveSupport/Concern

#3


0  

You can pull the name of a class from an instance and then constantize it.

您可以从实例中提取类的名称,然后对其进行实例化。

For example, given a class Thing:

例如,给定一个类Thing:

t = Thing.new
t.class.name
  # => "Thing"
t.class.name.constantize
  # => Thing

#1


3  

Ah.. found the solution almost right after I asked...

啊..我问了几乎就找到了解决方案......

self.class.all.each do |instance| ...

self.class.all.each do | instance | ...

#2


0  

if you want to extend the behavior of rails classes, then you are best of using ActiveSupport::Concern!

如果你想扩展rails类的行为,那么你最好使用ActiveSupport :: Concern!

http://apidock.com/rails/ActiveSupport/Concern

#3


0  

You can pull the name of a class from an instance and then constantize it.

您可以从实例中提取类的名称,然后对其进行实例化。

For example, given a class Thing:

例如,给定一个类Thing:

t = Thing.new
t.class.name
  # => "Thing"
t.class.name.constantize
  # => Thing