rails nameerror uninitialized constant class will occur if your rails console is not loaded with configuration of the class file containing method being called.
Basically this can happen if you happened to call the function from the class which is not loaded with configuration when your rails console/server was started.
Suppose you create a file named Util.rb in the lib folder of your Rails project.
And then if you want to call the function through command line i.e. rails console probably you will start rails console and and call the method get_date using class name Util as follows,
This will give you following error -
NameError: uninitialized constant Util
It means that your class was not loaded when the rails console was started
To resolve this problem your class has to be loaded in environment, this can be done in following way,
Open application.rb file of your Rails project
Add following line in application.rb
Your application.rb will look something like,
Thus, Setting autoload_paths for config in application.rb will result for - ruby files present in lib directory of your Rails project to get automatically loaded when your console is started. Calling method will not give rails nameerror uninitialized constant class error anymore.
Now, calling the method -
will return result as expected. As the class was loaded with configuration when your console was started thus Name resolution was successful.
Ultimately these kind of errors can be reduced if you configure your Rails application properly. Read Configuring Rails application to know more about configurations.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox