Harish Shetty's solution will not work for namespaced model files which are not stored directly in Rails.root/app/models but in a subdirectory. Although it correctly globs files in subdirectories, it then fails to include the subdir when turning the file name into a constant. The reason for this is, that the namespacing subdir is removed by this line:
klass = File.basename(file, ".rb").camelize.constantize rescue nil
Here is what I did to retain the namespacing subdir:
file.sub!(File.join(Rails.root, "app", "models"), '')
file.sub!('.rb', '')
klass = file.classify.constantize rescue nil
Here's the full modified solution:
def self.all_polymorphic_types(name)
@poly_hash ||= {}.tap do |hash|
Dir.glob(File.join(Rails.root, "app", "models", "**", "*.rb")).each do |file|
file.sub!(File.join(Rails.root, "app", "models"), '')
file.sub!('.rb', '')
klass = file.classify.constantize rescue nil
next unless klass.ancestors.include?(ActiveRecord::Base)
klass.
reflect_on_all_associations(:has_many).
select{ |r| r.options[:as] }.
each do |reflection|
(hash[reflection.options[:as]] ||= []) << klass
end
end
end
@poly_hash[name.to_sym]
end
Now, the method will turn /models/test/tensile.rb correctly into Test::Tensile before reflecting on its associations.
Just a minor improvement, all credit still goes to Harish!