类变量和扩展模块
我有一个如下所示的模块
module MyModule
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def foo
@@var = 1
end
def bar
puts @@var
end
end
end
class A
include MyModule
foo
end
class B < A; end
,但是
B.bar outputs '1'.
,我希望仅在调用 .foo 时才定义 .bar 。我尝试过,
module MyModule
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def foo
@@var = 1
extend SingletonMethods
end
module SingletonMethods
def bar
puts @@var
end
end
end
问题是
B.bar
返回错误“MyModule::SingletonMethods 中未初始化的类变量@@var”。如何才能使 .foo 中定义的变量可用于 .bar?
I have a module like the following
module MyModule
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def foo
@@var = 1
end
def bar
puts @@var
end
end
end
class A
include MyModule
foo
end
class B < A; end
so that
B.bar outputs '1'.
However, I would like to have .bar only be defined if .foo is called. I tried
module MyModule
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def foo
@@var = 1
extend SingletonMethods
end
module SingletonMethods
def bar
puts @@var
end
end
end
The problem is that
B.bar
returns the error "uninitialized class variable @@var in MyModule::SingletonMethods". How can I make it so that a variable defined in .foo is available to .bar?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 mattr_accessor 代替
use mattr_accessor instead
我能够使用 self 语法从模块访问类变量
现在调用 User.headers 给了我预期的结果
[:slug, :email, :crypted_password]
如果有人可以进一步解释为什么这在 ruby 中如此有效,请告诉我!
I was able to access class variables from a module using the self syntax
Now calling
User.headers
gives me the expected result of[:slug, :email, :crypted_password]
If anyone can shed more light on why this works exactly so in ruby, please let me know!