【问题标题】:Require file only if it exists仅当文件存在时才需要文件
【发布时间】:2014-05-12 15:06:08
【问题描述】:

也许有更好的方法来做到这一点。我希望能够动态加载一些路由。我计划在routes.rb 中使用静态路由,在custom_routes.rb 中使用自定义路由。然后在routes.rb的底部,我会这样做:

CustomRoutes.create if defined?(CustomRoutes)

为了使它工作,我必须要求 custom_routes.rb 仅当文件存在时,但如何?

custom_routes.rb

class CustomRoutes
  def self.create
    MyApplication.routes.draw do
      #...more routes here
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.2 ruby-1.8.7


    【解决方案1】:

    你应该简单地救援LoadError 异常:

    begin
      require "some/file"
    rescue LoadError
    end
    

    这是最传统的方式。

    【讨论】:

      【解决方案2】:

      有点像

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

      【讨论】:

        【解决方案3】:

        你可以这样做:

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

        虽然您可能想添加一些路径信息:

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

        【讨论】:

          猜你喜欢
          • 2016-09-05
          • 2016-09-11
          • 2012-10-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-14
          • 1970-01-01
          相关资源
          最近更新 更多