Search code examples
ruby-on-railsruby-on-rails-3.2ruby-1.8.7

Require file only if it exists


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

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'))