2016-07-15 38 views
0

我的应用程序有lib/project/errors其中包含了一些异常类,其中之一是ServiceException导轨 - 包括含有类模块为未初始化的常量错误

module Project 
    module Errors 
    class ServiceException < Exception 

     def initialize(message = nil) 
     super message 
     end 
    end 
    end 
end 

我想在我的GameService使用这个的:

module GameMan 


    class GameService 
    Blah blah 

    def validate(score) 
     raise Project::Errors::ServiceException.new('blah') 
    end 

    end 
end 

This works, 但是我讨厌写满的模块路径无处不在。有没有办法避免这种情况?

我已经试过

module GameMan 

    class GameService 
     include Project::Errors 
     Blah blah 

     def validate(score) 
     raise ServiceException.new('blah') 
     end 

    end 
end 

这给 uninitialized constant ServiceException错误。

config.autoload_paths += %W(#{config.root}/lib #{config.root}/app/services) already set in application.rb``

我在做什么错?

回答

1

这一切都是关于常量查找。

ServiceException定义在Project::Errors的范围内。当您参考ServiceException而没有添加前缀Project::Errors时,它会查找外部作用域中定义的类,并失败,因为没有。

您应该使用完整路径。

0
include Project::Errors 

替换上面的行至下面的行 包括项目::错误:: ServiceException

相关问题