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 }
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
.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With