我正在使用Rails 4.2.3。我在课堂上定义一个静态变量时遇到了麻烦。我有
class MainService < Abstractmy_objectFinderService
# class variables
@@my_object_desc_link_template = "https://results.Main.com/mobile/results/my_objects?_dc=1467745366092&eventID=21476"
…
event_link = MainService.my_object_data_link_template.sub( %r{intervalID=[^&]+}, "intervalID=#{interval_id}" )
.sub( %r{eventID=[^&]+}, "eventID=#{event_id}" )
.sub( %r{my_objectID=[^&]+}, "my_objectID=#{my_object_id}" )
但是当我运行我的代码时,我收到了错误
undefined method `my_object_desc_link_template' for MainService:Class
我还需要做什么才能成功定义静态变量?
答案 0 :(得分:0)
在Ruby中,您不会在方法块之外初始化变量。那就是说我会猜测你的代码示例做了什么并完全重写:
class MainService
BASE_URL = "https://results.Main.com/mobile/results/my_objects"
DEFAULT_PARAMS = {_dc: 1467745366092}
def self.event_link(interval_id, my_object_id, event_id)
params = {intervalID: interval_id,
eventID: event_id,
my_object_ID: my_object_id}
"#{BASE_URL}?#{DEFAULT_PARAMS.merge(params).to_query}"
end
end
然后使用event_link类方法从任何地方调用它:
MainService.event_link(1, 2, 3)
=> https://results.Main.com/mobile/results/my_objects?_dc=1467745366092&eventID=3&intervalID=1&my_object_ID=2"
如果您真的想要使用类变量,请告诉我。