如何列出包括关注点在内的所有模型

时间:2014-04-26 13:37:54

标签: ruby-on-rails

是否有一种简单的方法可以列出包含特定关注点的所有模型的类名?

类似的东西:

ActiveRecord.models.select{ |m| m.included_modules.include? MyConcernModule }

2 个答案:

答案 0 :(得分:12)

我有一个名为“Concerns :: CoursePhotoable”的问题。以下是包含它的两个模型:

> ActiveRecord::Base.descendants.select{|c| \
     c.included_modules.include?(Concerns::CoursePhotoable)}.map(&:name)
=> ["Course", "ProviderCourse"]

为了澄清,我的担忧实际上被命名为“Concerns :: CoursePhotoable”。如果你的名字叫“Fooable”,你只需将“Fooable”放在我的“Concerns :: CoursePhotoable”中。我将自己的问题命名为“可寻址”,以避免冲突。

编辑:当前版本的Rails使用include?。较旧的include

答案 1 :(得分:3)

如果这是您自己的关注点,您可以添加代码以跟踪其中包含的内容:

require 'active_support/concern'

module ChildTrackable
  extend ActiveSupport::Concern

  # keep track of what classes have included this concern:
  module Children
    extend self
    @included_in ||= []

    def add(klass)
      @included_in << klass
    end

    def included_in
      @included_in
    end
  end

  included do

    # track which classes have included this model concern
    Children.add self

  end

end

# access at:
ChildTrackable::Children.included_in

更新:以前的热切加载模型:

Rails.application.eager_load!