facebook twitter hatena line email

「Ruby/rails/autoload」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(rails5以降productionではエラーとなる)
(追加したautoloadの確認)
行19: 行19:
 
  bin/rails r 'puts ActiveSupport::Dependencies.autoload_paths'
 
  bin/rails r 'puts ActiveSupport::Dependencies.autoload_paths'
 
  /helloworld/lib
 
  /helloworld/lib
 +
 +
==呼び出しサンプル==
 +
app/controller/test_controller.rb
 +
class TestController < ApplicationController
 +
  def hello
 +
    test_service = TestService.new("test")
 +
    require 'logger'
 +
    log = Logger.new('/tmp/log')
 +
    log.debug(test_service.exec()) # test
 +
  end
 +
end
 +
 +
helloworld/lib/test_service.rb
 +
class TestService
 +
  def initialize(name)
 +
  end
 +
  def exec()
 +
      return "test"
 +
  end
 +
end

2017年11月8日 (水) 03:46時点における版

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("test")
   require 'logger'
   log = Logger.new('/tmp/log')
   log.debug(test_service.exec()) # test
 end
end

helloworld/lib/test_service.rb

class TestService
  def initialize(name)
  end
  def exec()
     return "test"
  end
end