문제

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
도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top