[Ruby] Use your own class in lib directory with Rails6

1 minute read

How to create and use your own class, This time I will introduce how to make it under root/lib.

environment

rails 6.0.3

application.rb settings

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 lib under autoload_paths. About autoload_paths here

Configuration under lib

lib
 ├── assets
 ├── asks
 └── utils
     └── hoge.rb

I created utils/hoge.rb. Let’s use a name that is easy to understand.

Contents of hoge.rb

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 take over 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

Finally

While writing this article, I found the following post. (The lack of research was revealed…)

A story that fixed autoload_paths to eliminate mystery errors

According to Rails Guaid “Before Rails 5, it was often done to include lib/ under autoload_paths, but currently it is not recommended to put the code in a place other than the app folder and target it for autoload.” Errors that are specific to the production environment may occur.

Since under app is included in autoload_paths by default, It seems good to use that.

So why does the lib directory exist? I wonder if those who are good at development use it properly.

That’s it for this new question. Daily devotion

Tags: ,

Updated: