Eki Eqbal Eki Eqbal - 6 months ago 30
Ruby Question

How can I add a services directory to the load path in Rails?

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?

Answer

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