In my Rails project, I want to add services
directory in app
folder and include some service objects.
So let's say I want to add app/services/foo/test.rb
which looks like:
module Services
module Foo
class Test
end
end
end
In my config/application.rb
I added:
config.paths.add File.join('app', 'services'), glob: File.join('**', '*.rb')
config.autoload_paths += Dir[Rails.root.join('app', 'services', '*')]
However when I try to load the files in console it doesn't work:
⇒ rails c
Loading development environment (Rails 4.1.4)
[1] pry(main)> Services::Foo::Test
NameError: uninitialized constant Services
Any help how can I solve this issue?
Rails automatically reloads classes and modules if application files in the autoload paths change. More precisely, if the web server is running and application files have been modified, Rails unloads all autoloaded constants managed by the main autoloader just before the next request is processed.
Ruby by default has a list of directories it can look through when you ask it to load a specific file. This is stored in a variable: $: This is the load path. It initially includes the libdir, archdir, sitedir, vendordir and some others and is information Ruby holds about itself. If you type ruby -e 'puts $LOAD_PATH'
An initializer is any file of ruby code stored under /config/initializers in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks and plugins are loaded.
First of all, the code under app
folder will be loaded without any config.
I think the problem was the folder structure doesn't match with your class definition.
So this config will work:
app/services/foo/test.rb
module Foo
class Test
end
end
My clue is, for example we have app/controllers/api/v1/users_controllers.rb
and the class constant will be Api::V1::UsersController
, not Controllers::Api::V1::UsersController
Update
Conventionally, we usually use FooServices
instead of Foo
, it is clearer, for example:
app/services/foo_services/bar_parser.rb
module FooServices
class BarParser
# Do stuff
end
end
So we understand that every class inside foo_services
folder is a service which related to Foo
After add new dir, reload spring
spring stop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With