4

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
Josh M.
  • 23,573
  • 23
  • 96
  • 160

3 Answers3

4

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'))
Shadwell
  • 32,730
  • 14
  • 91
  • 94
0

Something like

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

jjk
  • 516
  • 7
  • 15
0

You should simply rescue on LoadError exception:

begin
  require "some/file"
rescue LoadError
end

This is the most conventional way.

skalee
  • 10,976
  • 6
  • 47
  • 54