How to create and use your own class, This time, I will introduce how to make it under root / lib.
rails 6.0.3
application.rb
module Myapp
class Application < Rails::Application
config.load_defaults 6.0
config.paths.add 'lib', eager_load: true #Add this
end
end
Add under lib to autoload_paths. About autoload_paths here
lib
├── assets
├── asks
└── utils
└── hoge.rb
I have created utils / hoge.rb. Let's give it a descriptive name.
hoge.rb
class Utils::Hoge
end
Or
hoge.rb
module Utils
class Hoge
def greeting
'hello'
end
end
end
Let's define a class with the name of the parent directory as the namespace. By doing this, you can hijack the rules of autoload_paths and call it as follows.
application_controller.rb
class ApplicationController < ActionController::Base
hoge = Utils::Hoge.new
hoge.greeting
#=> hello
end
While writing this article, I found the following post. (The lack of research was revealed ...)
Fixed autoload_paths to eliminate mystery error
According to Rails Guaid "Before Rails 5, it was common to include lib / and below in autoload_paths, but now it is not recommended to put the code in a location other than the app folder and make it an autoload target." It is said that an error specific to the production environment may occur.
Since the app is included in autoload_paths by default, It seems good to use that.
So why does the lib directory exist? I wonder if people who are good at development use it properly.
That's all for this time, when new questions have arisen. Dedicated every day
Recommended Posts