Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4610

How to check if a Rails model is defined? [duplicate]

$
0
0

I'm using a Ruby on Rails 5.2.8 and Ruby 2.7.8 version and I have found a bug in code. The code should check at runtime if a model is defined. At first I tried to use the defined? method, but because the development environment lazy loads the modules I have encountered unexpected (for me) behaviour:

defined?(ModelToCheck) #=> nilModelToCheckdefined?(ModelToCheck) #=> true

so only after using the model it appears to be defined. What is the best way to check if it is defined?

P.S.

the option which configures the lazy loading is:

# config/environments/development.rbExampleApp::Application.configure do  config.eager_load = false  # rest of the config  # ...end

For now I tried to use also Object.const_defined? method, but the same story again.

I have two ideas:

  • don't check at runtime if the model is defined at all
  • use a beginrescue blocks to handle NameError when it is not defined, however it is ugly and I wouldn't like to use it if I could

Viewing all articles
Browse latest Browse all 4610

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>