鉴于以下内容:
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
在pry会话中,调用request_url会产生:
"@@object_resource was not defined"
但@@ object_resource设置为“sr”。
我的想法是,对于每个类,我只需要包含RESTable模块,并且调用request_url将根据我所包含的类的@@ object_resource给出正确的URL。
更一般地说,如何从模块中调用类变量?
答案 0 :(得分: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