LoginSignup
4
4

More than 5 years have passed since last update.

Railsでroutes定義を複数ファイルに分けて自動ロードする

Last updated at Posted at 2017-03-15

Railsでルーティングを定義する場合、config/routes.rbに記載しますが、ルーティングが多くなってきたり、サブドメインを管理する場合には分けて管理したくなります。

そこで、config/routesディレクトリに分割したルーティング定義を配置し、開発時に変更が自動で反映されるようにします。Rails5.0.2で確認しているので、自動読み込みの設定方法はRails4などと多少変わっていると思います。

config/application.rb

設定ファイルconfig/application.rbに以下のように追記します。

config.paths.add 'config/routes', eager_load: true

config/routes.rb

続いて、標準のルーティング定義であるconfig/routes.rbで分割したルーティング定義を読み込みます(Rails.application.routes.draw do内に記述します)。

  Dir.glob(File.expand_path("#{Rails.root}/config/routes/**/*.rb", __FILE__)).each do |file|
    instance_eval(File.read(file))
  end

従来の対応方法

以前に同様のことを実現するために調べた際に以下のようなコードをconfig/initializersに配置していました。

if Rails.env.development?
  class RoutesReloader
    ROUTES_PATH = Dir.glob("config/routes/*.rb")

    def initialize(app)
      @app = app

      @routes_reloader = ActiveSupport::FileUpdateChecker.new(ROUTES_PATH) do
        Rails.application.reload_routes!
      end
    end

    def call(env)
      @routes_reloader.execute_if_updated

      @app.call(env)
    end
  end

  Rails.application.config.middleware.use RoutesReloader
end

上記では、開発中に何かしらエラーが発生した際にエラー箇所が最後まで表示されない問題がありましたので、改めて自動読み込みの設定を調べてみました。

その他、最適な設定は随時アドバイスお願いします。


Created with NOOTO

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4