2012-10-21 155 views
3

我有一个像这样的rails设置。Rails加载类更改,而无需重新启动服务器

应用程序/服务/ TestService.rb

class TestService 

    def self.doSomething 
    return 'Hello World!' 
    end 

end 

我使用控制器上的这个文件。

require 'TestService' 

class IndexController < ApplicationController 

    def index 
    @message = TestService.doSomething 
    end 

end 

我还在config文件夹中的application.rb中添加了这个,这样rails自动载入服务文件夹中的类。

config.autoload_paths += %W(#{config.root}/app/service) 

但是,该应用程序似乎没有拿起TestService类的更新。我该如何解决这个问题,以便在不重启服务器的情况下显示TestService类中的更改。

回答

2

尝试加载包含可重载常量的文件时,不要使用require

通常情况下,您不需要做任何特殊的事情即可使用该常量。您将直接使用常量,而不必使用require或其他任何东西。

但是,如果你想和你的代码干干净净,ActiveSupport为您提供不同方法,你可以用它来加载这些文件:require_dependency

require_dependency 'test_service' 

class IndexController < ApplicationController 
    ... 
end 

虽然这是令人困惑,你会试图成为干干净净的,并明确加载包含TestService文件,但没有明确加载包含文件ApplicationController ....

你并不需要改变autoload_paths配置。


更新1

为了让Rails的查找和加载常数(类和模块),你需要做到以下几点:

你必须确保在每一个增值的恒定你的应用程序位于具有正确文件名的文件中。该文件必须始终位于app的某个子目录中,例如app/modelsapp/services或任何其他子目录。如果常量名为TestService,则文件名必须以test_service.rb结尾。

该算法是:"TestService".underscore + ".rb" #=> "test_service.rb"

filename_glob = "app/*/" + the_constant.to_s.underscore + ".rb" 

因此,如果常数是TestService,则水珠是app/*/test_service.rb。所以坚持在app/services/test_service.rb的常数将工作,app/models/test_service.rb,虽然后者是不好的形式。如果常量为SomeModule::SomeOtherModule::SomeClass,则需要将该文件放入app/*/some_module/some_other_module/some_class.rb

+0

添加require_dependency ...似乎工作。但是,如果我删除它,则不会加载对TestService的更改。 – 3coins

+0

撤销对“autoload_paths”配置的更改。根本不要设置该配置。 – yfeldblum

+0

我已经删除了。如果我在控制器中没有require或require_dependency,则获取此错误。未初始化的常量IndexController :: TestService – 3coins

0

你说你的文件在app/server,但你自动加载app/service。哪个是对的?

将您的文件重命名为app/service/test_service.rb并且自动装带器应该工作。 Rails在自动加载路径中查找基于snake_的文件名。一旦你的自动加载行为正确,你也不需要手册require

+0

我的错误,文件在应用程序/服务,我更新了帖子。 – 3coins

相关问题