2017-08-16 51 views
0

我有2個項目,即我已經制成,在其它模塊像這樣拉大模塊「共同編碼」項目:紅寶石:模塊內調用寶石子類產生未初始化的常數

這裏是文件夾結構「我的常見項目」:

  • 我的常見項目
    • 共同
      • 休息,client.rb
      • 其他Ruby文件與模塊...
    • common.rb
    • 的Gemfile
    • 等...

常見。 rb

require 'bundler' 
Bundler.require 
require_relative './common/rest_client.rb' 
... 

module Common 
    include RestClient 
    # include other modules here... 

休息,client.rb

module Common 
    module RestClient 

    def call_rest_service_get(url) 
    begin 
     response = RestClient.get(url, {accept: :json}) 
    rescue RestClient::Exception => err 
     return err.response 
    else 
     return response 
    end 
    end 
end 

的Gemfile

# frozen_string_literal: true 
source 'https://rubygems.org' 

gem 'rest-client' 
# other gems here... 

然後在名爲 「我的 - 其他項目」 另一個項目:

  • 我,其他項目
    • 服務
      • service.rb

service.rb

require_relative './../../../common/common.rb' 

class Service 

    include Common 

    def get_rest_data 
    call_rest_service_get('http://some-url.com) 
    end 
end 

我得到一個錯誤時,該代碼使得它在其他客戶端的救援塊.rb:

NameError - uninitialized constant Common::RestClient::Exception 

我不知道如何解釋我的問題,但沿線的某處似乎常見模塊正在失去其他客戶端模塊上的其他類,在本例中爲Exception。有人可以解釋爲什麼這種結塊方法,然後包括許多模塊不起作用嗎?

回答

1

既然你有一類稱爲Common::RestClient和使用的是紅寶石的寶石,它定義一個類RestClient,當你你Common模塊中,你需要用::前綴引用寶石RestClient,否則,就認爲你在說關於Common::RestClient

module Common 
    module RestClient 

    def call_rest_service_get(url) 
    begin 
     response = ::RestClient.get(url, {accept: :json}) 
    rescue ::RestClient::Exception => err 
     return err.response 
    else 
     return response 
    end 
    end 
end