Question

Perhaps there's a better way to do this. I want to be able to load some routes dynamically. I was planning on having static routes in routes.rb, and custom routes in custom_routes.rb. Then at the bottom of routes.rb, I would do:

CustomRoutes.create if defined?(CustomRoutes)

In order for this to work I have to require custom_routes.rb only if the file exists, but how?

custom_routes.rb

class CustomRoutes
  def self.create
    MyApplication.routes.draw do
      #...more routes here
    end
  end
end
Was it helpful?

Solution

You can do:

require 'custom_routes' if File.exists?('custom_routes.rb')

Although you might want to add some path information:

require 'custom_routes' if File.exists?(File.join(Rails.root, 'lib', 'custom_routes.rb'))

OTHER TIPS

You should simply rescue on LoadError exception:

begin
  require "some/file"
rescue LoadError
end

This is the most conventional way.

Something like

require File.expand_path("../../config/custom_routes", __FILE__) if File..exists?("../../config/custom_routes.rb")

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top