I am currently working on a Ruby on Rails (RoR) application and needed a mechanism to load routes that are generated into a file by another tool. After some experimentation I came up with the following solution.
In a Ruby on Rails application the routing is configured using the
config/routes.rb file. The routes are defined using the
draw method of
ActionController::Routing::Routes class like this:
ActionController::Routing::Routes.draw do |map|
...
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
The block is executed with a local variable
map in the scope. I wanted to insert routes defined in a separate file that is generated by another tool. To do that I tried to use the
load or
require methods. However I realized that it will not work because the
load or
require methods reset the scope to the top level. So I came up with the following:
# insert routes from generated file
instance_eval(File.read(File.expand_path(File.dirname(__FILE__)) + "/generated-routes.rb"))
Basically it is evaluating the contents of a file in the instance (current) scope. The
File.expand_path(File.dirname(__FILE__)) simply computes the path to folder that contains routes.rb file. To that I append the name of generated routes file which lives next to routes.rb file.
Is there a better/idiomtic way to do this?