【问题标题】:How to get class variable into module如何将类变量放入模块
【发布时间】:2019-09-30 23:53:02
【问题描述】:

我无法通过类变量覆盖模块变量。

module Main
  class Traks
    @@endpoint ='/trakings'
    class << self
      include ViewTrait
    end
  end 
end

我的特质模块

module Main
  module ViewTrait
    def view(id:, options: "")
      Response::new("#{@@endpoint}/#{id}#{options}").resource(id: id).get
    end
  end
end

在 ViewTrait 中,我无法访问已在 Traks 类中定义的 @@endponint。任何人都可以告诉我我出了什么问题。

【问题讨论】:

  • 我可以告诉你,如果你用单个 @ 替换 @@,这将起作用
  • @maxpleaner- 我已经尝试过了,但我在 ViewTrait 模块中得到了空字符串。
  • 请注意class &lt;&lt; self; include ViewTrait; endextend ViewTrait 相同。见Object#extend
  • @CarySwoveland- 问题是将类变量访问到其他模块方法中。
  • isn't @@endpoint in the ViewTrait 模块是说self.@@endpoint 在这种情况下,self 不是 ViewTrait 模块吗?如果您调用正确的接收器,它应该可以工作吗?

标签: ruby ruby-on-rails-3 ruby-on-rails-4 rubygems


【解决方案1】:

在 ViewTrait 中,我替换了 @@endpointself.class_variable_get(:@@endpoint),我可以将类变量访问到模块中。希望这对其他人有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多