facebook twitter hatena line email

Ruby/rails/autoload

提供: 初心者エンジニアの簡易メモ
2017年11月8日 (水) 03:53時点におけるAdmin (トーク | 投稿記録)による版 (呼び出しサンプル)

移動: 案内検索

autoloadを使うための準備

config/application.rb

module Helloworld
  class Application < Rails::Application
    config.autoload_paths += %W(#{config.root}/lib) # これを追加
  end
end

rails5以降productionではエラーとなる

以下もapplication.rbに追加

config.paths.add 'lib', eager_load: true


rails5ではあまりautoloadは推奨ではない。

参考:https://qiita.com/K_Yagi/items/edc46fd976526279312b

追加したautoloadの確認

bin/rails r 'puts ActiveSupport::Dependencies.autoload_paths'
/helloworld/lib

呼び出しサンプル

app/controller/test_controller.rb

class TestController < ApplicationController
 def hello
   test_service = TestService.new("test1")
   require 'logger'
   log = Logger.new('/tmp/log')
   log.debug(test_service.exec()) # test1
 end
end

helloworld/lib/test_service.rb

class TestService
  def initialize(name)
     @name = name
  end
  def exec()
     return @name
  end
  attr_accessor :name
end