在生产中自动加载

时间:2014-05-26 14:01:17

标签: ruby-on-rails heroku production-environment rails-api ruby-on-rails-4.1

我将所有控制器声明为

class Api::V1::SomeController < Api::V1::ApiController; (...); end

,其中

class Api::V1::ApiController < ApplicationController; end

我的所有控制器都放在/app/controllers/api/v1/*_controller.rbApplicationController位于app/controllers/application_controller.rb下。

在开发过程中一切正常,但我在生产中要求和加载包含在API版本命名空间中的控制器时遇到问题。

在生产环境(本地或heroku)中,我得到了:LoadError (Unable to autoload constant Api::V1::SomeController, expected /app/app/controllers/api/v1/some_controller.rb to define it):

在生产环境中配置app/config/environments/production.rb并要求版本控制api的正确方法是什么。

1 个答案:

答案 0 :(得分:2)

我非常确定您会通过采用模块化方法来定义所有命名空间类来解决此问题。例如:

module Api
  module V1
    class SomeController < ApiController
      # ...
    end
  end
end

module Api
  module V1
    class ApiController < ::ApplicationController
      # ...
    end
  end
end

使用此模式消除了Rails中自动加载的名称空间的歧义。自动加载是一种相当复杂的机制......(在开发和生产之间似乎表现得不同!)如果您想了解更多内部工作原理this article,那么值得阅读。

<强>更新

::中的::ApplicationController表示&#34;没有名称空间&#34;或者#34;默认命名空间&#34;。在这种情况下可能不需要该部分,因为您可能只定义了一个ApplicationController常量。

这种方法产生的不同之处在于它确保Rails不会跳过&#34;跳过&#34;可以这么说,你的定义不变。我上面链接的文章通过示例解释了它。