简体   繁体   English

如何在Rails中的gem中将不存在的类添加到现有模块

[英]How can I add non-existing class to a exiting module in gem in rails

I understand that I can overwrite or to add on to a class that's already existed but I want to add additional class to an existing module(in a gem) so I can keep in constant when I call it. 我知道我可以覆盖或添加到已经存在的类中,但是我想向现有模块(在gem中)添加其他类,以便在调用它时可以保持不变。 Cuz I though that when rails load up the lib. 因为我那是当rails加载lib的时候。 They should recognize it. 他们应该意识到这一点。

See following example. 请参见以下示例。 I would like to add the NotAcceptableHttpResponseError to the same HttpService module 我想将NotAcceptableHttpResponseError添加到同一HttpService模块

Example module HttpService (in a gem) only have a decent amounts of exceptions class and I would like to add some custom one for others 示例模块HttpService(在gem中)只有相当数量的exceptions类,我想为其他类添加一些自定义类

config/application.rb 配置/ application.rb中

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

In the gem/exceptions.rb 在gem / exceptions.rb中

module HttpService
   class BadHttpResponseError
     xxx
     xxx
   end

In lib/http_service/exceptions.rb 在lib / http_service / exceptions.rb中

module HttpService
   class NotAcceptableHttpResponseError
     xxx 
     xxx
   end
end

The Error 错误

NameError(uninitialized constant HttpServices::NotAcceptableHttpResponseError)

Rails 3 does not autoload lib file Rails 3不会自动加载lib文件

1) add this in config/application.rb : 1)将其添加到config / application.rb中

config.autoload_paths += Dir["#{config.root}/lib/**/"] config.autoload_paths + = Dir [“#{config.root} / lib / ** /”]

2) Name of the folder should be the same as the module name and the name of the file should be same as the name of the class(rails naming convention should be followed) 2)文件夹名称应与模块名称相同,文件名称应与类名称相同(应遵循rails命名约定)
Rename exceptions.rb to name of the class ie, not_acceptable_http_response_error.rb 将exceptions.rb重命名为类的名称,即not_acceptable_http_response_error.rb

or 要么

add in config/initializers/require.rb 添加config / initializers / require.rb

require "#{Rails.root}/lib/http_service/exceptions" 

Figured out the Answer. 找出答案。 It's actually not ideal to modify module that's in the gem. 修改gem中的模块实际上并不理想。 since you will have to fork the project in the gem file and maintain the version if they are updated 因为您必须将项目保存在gem文件中,并在更新后维护版本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM