Refactoring a Large Routes.Rb File in Rails 4

Refactoring a large routes.rb file in rails 4

In one of my larger applications I use the following segment of code inside of my config/routes.rb file.

class ActionDispatch::Routing::Mapper
def draw(routes_name)
instance_eval(File.read(Rails.root.join("config/routes/#{routes_name}.rb")))
end
end

YourApplication::Application.routes.draw do
# Loads config/routes/common.rb
draw :common
# Loads config/routes/another.rb
draw :another
end

Rails 4 initially had support for draw :routeName but it was removed as it did not show any improvements. (I dont know ^.^) You can check out the git commit doing so here: https://github.com/rails/rails/commit/5e7d6bba79393de0279917f93b82f3b7b176f4b5

rails 4: split routes.rb into multiple smaller files

This was removed from Rails 4 in June of 2012. 5e7d6bba reverts an earlier commit, removing support for loading multiple external route files as part of config.rb.

For further read, check out the comments on this commit.

How to refactor a large Ruby class?

So, extracting conclusions from the comments, I liked these 2 ideas:

  • Common sense. Only you as the developer know how the code should be structured, so tools can only suggest, but you have the final word. Rubocop can be configured through comments in the code to disable some checks.
  • In case of refactor, private methods in a controller could be extracted into a helper.

Rails additional configuration in initializer

Not answering your question directly, but providing a different (better?) approach to what you're trying to do:

Check out this alternative that DHH posted in a gist.

Split seeds.rb file

Since your seeds.rb file is Ruby, then you can do anything in it you can do in Ruby. Like routes.rb and Gemfile you can get quite creative if required.

Just be sure that you don't do anything so crazy it would actually require some debugging. As long as you keep your actions clear, there should be no confusion. That is, don't use custom helper methods that are defined in some other file that could malfunction and would have to be tracked down by hand. It's probably best to stick to the simplest solution when doing things like this.



Related Topics



Leave a reply



Submit