I wan't to set a class variable of a class from the outside(via attr_accessor), and then access it from inside one of its objects. I'm using ruby 1.9.2. This is my code:
class Service
def initialize(id)
@my_id = id
end
class << self
attr_accessor :shared_id
end
def system_id
@my_id + @@shared_id
end
end
If I set Service.shared_id = "A2"
, and then call Service.new("A").system_id
, this doesn't return "AA2". It displays the following error:
uninitialized class variable @@shared_id in Service
The behaviour is like if I didn't set the Service开发者_JS百科.service_id. Can someone please explain why this happens?
attr_accessor
creates methods to manipulate instance variables — it does not create instance or class variables. To create a class variable, you must set it to something:
@@shared_id = something
There's no helper method to generate accessor for class variables, so you have to write them yourself.
However, class variables, because of their weird lookup rules, are rarely used — avoided, even. Instead, instance variables at class-level are used.
class Service
@shared_id = thing
class << self
attr_accessor :shared_id
end
def system_id
# use self.class.shared_id; you could add a shared_id helper to generate it, too.
end
end
How about cattr_accessor
?
Remember that @@class_var
is global for all classes.
精彩评论