How to list all models including a concern

杀马特。学长 韩版系。学妹 提交于 2019-12-05 00:16:51

问题


Is there a simple way to list the class names of all models that include a particular Concern?

Something like:

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

回答1:


I have a concern named "Concerns::CoursePhotoable". Here's the two models that include it:

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

To clarify, my concern is really named "Concerns::CoursePhotoable". If yours was named "Fooable" you'd simply put "Fooable" where I have "Concerns::CoursePhotoable". I namespace my concerns to avoid conflicts with say "Addressable".

EDIT: Current versions of Rails use include?. Older used include.




回答2:


If it's your own Concern, you could add code to track when it's included:

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

update: to eager load models prior:

Rails.application.eager_load!


来源:https://stackoverflow.com/questions/23311679/how-to-list-all-models-including-a-concern

标签

工具导航Map