Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to exclude all models from engine? #4

Closed
bjensen opened this issue Feb 11, 2020 · 6 comments
Closed

How to exclude all models from engine? #4

bjensen opened this issue Feb 11, 2020 · 6 comments

Comments

@bjensen
Copy link

bjensen commented Feb 11, 2020

I tried adding this to the apartment initializer:

engine_models = myEngine.constants.map {|c| myEngine.const_get(c) }.select do |const|
  const.class == Class && const < ActiveRecord::Base
end

config.excluded_models = %w[User] + engine_models

This works perfectly when run in the console, however engine_models is empty when its being executed as part of initialisation. Does anyone have a good idea?

This is in Rails 6.0.2.1

@jean-francois-labbe
Copy link

Hi @bjensen I think this is because in development classes are lazy loaded so when the initializer is executed models are not loaded yet.

@bjensen
Copy link
Author

bjensen commented Feb 11, 2020

I think you are right..but do you have any suggestions as to how to get it working in development except for actually having to cut and paste every model name and remember to add to this list whenever we add a new model etc?

@jean-francois-labbe
Copy link

I don't have the solution for this issue, but you should check rails eager_loading: https://guides.rubyonrails.org/autoloading_and_reloading_constants.html#eager-loading

@rpbaltazar
Copy link
Contributor

rpbaltazar commented Feb 17, 2020

@bjensen You might be able to get around with something close to what you have:

engine_models = myEngine.constants.map {|c| myEngine.const_get(c) }.select do |const|
const.class == Class && const < ActiveRecord::Base
end

engine_models.each do {|em| require em }

config.excluded_models = %w[User] + engine_models

Out of curiosity, what is the use case behind this?

EDIT: Forget what i just said. I've read through the thing again... I don't think that you'll be able to get around it without loading the classes.

The other option (more prone to errors) is to try to convert the table names onto models. Eg.

models = ActiveRecord::Base.connection.tables.map do |model|
  begin
    model.classify.constantize
  rescue NameError => e
    nil
  end
end

models.compact!

@rjayroach
Copy link

Does ActiveRecord::Base.connection.tables get the job done?

@rpbaltazar
Copy link
Contributor

Closing this as it doesn't seem needed anyhow else. If this becomes an issue we can look at the use case

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants