简体   繁体   English

Ruby:在模块中调用类方法

[英]Ruby: invoke class methods in a module

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. 就参数而言,假设此方法将某些属性与另一个相同类型的实例"match"则将字符串"match"放入。

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. 但是,我不能在这里简单地调用self.all ,因为self是一个实例。 How do I call the class method all from here? 如何调用类的方法all从这里?

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

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

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 http://apidock.com/rails/ActiveSupport/关注

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

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

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