ruby access static variable
class A
@@ololo = 1
end
A::ololo
A.new.ololo
NoMethodError: undefined method `ololo'
okey. I need an attr_reader
class B
@@ololo = 1
attr_reader :ololo
end
A::ololo
NoMethodError: undefined met开发者_如何学运维hod `ololo'
A.new.ololo
=> nil
wtf? is there any limit for ruby accessors?
class C
@@ololo = 1
def self.ololo
@@ololo
end
def ololo
@@ololo
end
end
C::ololo
=> 1
C.new.ololo
=> 1
Ruby men usually say "yeah! pretty good!". is this pretty good? Can anyone provide shorter code?
You can't do what you want to do :)
@harald is right. attr_reader
will define GETTER only for instance variable, for "static" (aka "class variables") you need to define setter and getter by yourself:
class A
@@ololo = 1
# instance level
# getter
def ololo
@@ololo
end
# setter
def ololo=trololo
@@ololo = trololo
end
# and class level
# if you need it
# getter
def self.ololo
@@ololo
end
# setter
def self.ololo=trololo
@@ololo = trololo
end
end
So:
a = A.new
b = A.new
A.ololo
#=> 1
a.ololo
#=> 1
A.ololo = 100
A.ololo
#=> 100
a.ololo
#=> 100
b.ololo
#=> 100
a.ololo = 4
A.ololo
#=> 4
...
Shorter one:
class A
@ololo = 1
class << self
attr_accessor :ololo
end
end
attr_accessor :ololo
defines the methods ololo
and ololo=
which work against an instance variable named @ololo. So what happens when you try to access A::ololo
ruby will find your instance method ololo
and fail since you're trying to call it as a class method.
Yes, you can.
class A
cattr_accessor :ololo
@@ololo = 1
end
class B
A.ololo #Gets class variable "ololo" from class A
end
This is basically a Ruby on Rails feature. However, outside Rails, you can obtain the functionality from the Ruby Facets gem:
https://github.com/rubyworks/facets/blob/master/lib/core-uncommon/facets/module/cattr.rb
See this discussion: cattr_accessor outside of rails
精彩评论