如何让Rails开发服务器在更改时重新加载我的类?

时间:2014-01-18 06:10:53

标签: ruby-on-rails ruby ruby-on-rails-4

我有这个类,服务器没有取消更改,除非我杀死服务器并重新加载它。我的所有其他课程都会自动更新。如何让Rails服务器(WebBrick)在不必杀死服务器的情况下获取此类的更改?

我看到了这些问题,但我没有使用模块:Rails 3.2.x: how to reload app/classes dir during development?

我看到了这个问题,但没有答案:Rails Engine: How to auto reload class upon each request?

class UsersController < ApplicationController
  require 'PaymentGateway'
  def method
   result = PaymentGateway::capture

这是我想要在更改时自动重新加载的类。它与app / controllers /

位于同一目录中
class PaymentGateway < ApplicationController 
  def self.capture

Rails 4.0.0

3 个答案:

答案 0 :(得分:2)

您的代码最初存在一些问题。

    一个班级里面的
  1. require什么也没做。要获得mixins,请使用includeextend
  2. 课程不适用于包含或扩展。模块确实。
  3. 您无需在'/ app`
  4. 中输入文件

    我不知道你的真正目的是什么,如果你想在PaymentGateway中重用该方法,将其设置为模块并将其包含在其他模块中。

    module PaymentGateway
      extend ActiveSupport::Concern
    
      module ClassMethods
        def capture
          # ...
        end
      end
    end
    
    # Then in controller
    class UsersController < ApplicationController
      include PaymentGateway
    end
    

    通过此更改,在每个对UsersController操作的请求中,include宏将在运行时执行,您无需重新启动服务器。

答案 1 :(得分:2)

  1. 请勿使用require。这只适用于第三方图书馆。
  2. 将文件名更改为snake_case.rb。 Rails会自动获取更改。

答案 2 :(得分:1)

我会建议一些事情。

首先,PaymentGateway类应该是lib/payment_gateway的一部分,以便它可以在您的应用程序的任何部分中使用。

其次,如果需要多态控制器,请使用控制器继承模式

class BaseController < ApplicationController
end

class UsersController < BaseController
end