Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all models including a concern

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 }
like image 935
rigyt Avatar asked Apr 26 '14 13:04

rigyt


2 Answers

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.

like image 117
Philip Hallstrom Avatar answered Oct 20 '22 01:10

Philip Hallstrom


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!
like image 25
Eric London Avatar answered Oct 20 '22 00:10

Eric London