2013-08-12 278 views
1

鑑於以下內:訪問類變量模塊方法

module RESTable 
    BASE_URL = "http://url.domain/api/rest" 
    LOGIN_URL = "#{BASE_URL}/login" 
    LOGOUT_URL = "#{BASE_URL}/logout" 

    def request_url 
    "#{BASE_URL}/mbo/#{@@object_resource}/_format=json" 
    rescue NameError 
    p "@@object_resource was not defined" 
    end 
end 

class ServiceRequests 
    include RESTable 
    @@object_resource = "sr" 

    def initialize 
    binding.pry 
    end 
end 

在撬會話,呼叫request_url收率:

"@@object_resource was not defined" 

但@@ object_resource被設定爲 「SR」。

這個想法是,對於每個類,我只包含RESTable模塊,調用request_url會根據我包含的類的@@ object_resource爲我提供正確的URL。

更一般地說,如何從模塊中調用類變量?

回答

0

我通過在模塊上聲明@@ object_resource解決了這個問題,如果@@ object_resource保持不變(即空白),則會引發錯誤。

下面是更新模塊:

module RESTable 
    BASE_URL = "http://url.domain/api/rest" 
    LOGIN_URL = "#{BASE_URL}/login" 
    LOGOUT_URL = "#{BASE_URL}/logout" 
    @@object_resource = "" 

    def request_url 
    raise StandardError, "@@object_resource can't be blank" if @@object_resource == "" 
    "#{BASE_URL}/mbo/#{@@object_resource}/_format=json" 
    rescue NameError 
    p "@@object_resource was not defined" 
    end 
end