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 method `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?
Yes, you can.
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
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:So:
...
Shorter one:
attr_accessor :ololo
defines the methodsololo
andololo=
which work against an instance variable named @ololo. So what happens when you try to accessA::ololo
ruby will find your instance methodololo
and fail since you're trying to call it as a class method.