Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 911
Eki Eqbal Avatar asked May 11 '16 07:05

Eki Eqbal


People also ask

What is autoloading in Rails?

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.

What is load path in Ruby?

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'

What are Initializers in Rails?

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.


2 Answers

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

like image 91
Hieu Pham Avatar answered Nov 15 '22 22:11

Hieu Pham


After add new dir, reload spring spring stop

like image 23
Adam Ludian Avatar answered Nov 15 '22 21:11

Adam Ludian