I have a rails setup that is something like this.
app/service/TestService.rb
class TestService
def self.doSomething
return 'Hello World!'
end
end
I am using this file in the controller.
require 'TestService'
class IndexController < ApplicationController
def index
@message = TestService.doSomething
end
end
I also added this in application.rb inside the config folder, so that rails autoload classes in service folder.
config.autoload_paths += %W(#{config.root}/app/service)
But the application doesn’t seem to pick up updates to TestService class. How can I fix this, so that changes in TestService class show up without restarting the server.
Do not use
requirewhen attempting to load a file containing a reloadable constant.Normally, you will not need to do anything special to be able to use that constant. You will just use the constant directly, without having to use
requireor anything else.But if you want to be squeaky clean with your code,
ActiveSupportprovides you with a different method that you can use to load these files:require_dependency.Although it’s confusing that you would attempt to be squeaky clean and explicitly load the file containing
TestServicebut not explicitly load the file containingApplicationController….You do not need to change the
autoload_pathsconfig.Update 1
In order to let Rails find and load your constants (classes and modules), you need to do the following:
You must be sure that every reloadable constant in your application is in a file with the right filename. The file must always be in some subdirectory of
app, such asapp/modelsorapp/servicesor any other subdirectory. If the constant is namedTestService, the filename must end withtest_service.rb.The algorithm is:
"TestService".underscore + ".rb" #=> "test_service.rb".So if the constant is
TestService, then the glob isapp/*/test_service.rb. So sticking the constant inapp/services/test_service.rbwill work, as willapp/models/test_service.rb, although the latter is bad form. If the constant wereSomeModule::SomeOtherModule::SomeClass, you would need to put the file inapp/*/some_module/some_other_module/some_class.rb.