Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
997 views
in Technique[技术] by (71.8m points)

rails 4: split routes.rb into multiple smaller files

I would like to split my routes in rails 4 application. For rails 3 the question has been answered a few times like:

What would be the correct way to do this in rails 4 + how to get control over the order the routes get loaded?

Suggested from the rails 3 questions:

application.rb

    config.paths['config/routes'] = Dir["config/routes/*.rb"]

Fails with:

/Users/jordan/.rvm/gems/ruby-2.0.0-head@books/gems/railties-4.0.0/lib/rails/application/routes_reloader.rb:10:in `rescue in execute_if_updated': Rails::Application::RoutesReloader#execute_if_updated delegated to updater.execute_if_updated, but updater is nil:

@route_sets=[#]> (RuntimeError)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've manage that this way:

# config/application.rb
config.autoload_paths << Rails.root.join('config/routes')

# config/routes.rb
Rails.application.routes.draw do
  root to: 'home#index'

  extend ApiRoutes
end

# config/routes/api_routes.rb
module ApiRoutes
  def self.extended(router)
    router.instance_exec do
      namespace :api do
        resources :tasks, only: [:index, :show]
      end
    end
  end
end

Here I added config/routes directory to autoload modules defined in it. This will ensure that routes are reloaded when these files change.

Use extend to include these modules into the main file (they will be autoloaded, no need to require them).

Use instance_exec inside self.extended to draw routes in the context of router.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...