Talespin_Kit Talespin_Kit - 4 months ago 13
Ruby Question

Attr_accessor on class variables

attr_accessor
does not work on the following code. The error says "
undefined method 'things' for Parent:Class (NoMethodError)
":

class Parent
@@things = []
attr_accessor :things
end
Parent.things << :car

p Parent.things


However the following code works

class Parent
@@things = []
def self.things
@@things
end
def things
@@things
end
end
Parent.things << :car

p Parent.things

Answer

attr_accessor defines accessor methods for an instance. If you want class level auto-generated accessors you could use it on the metaclass

class Parent
  @things = []

  class << self
    attr_accessor :things
  end
end

Parent.things #=> []
Parent.things << :car
Parent.things #=> [:car]

but note that this creates a class level instance variable not a class variable. This is likely what you want anyway, as class variables behave differently then you might expect when dealing w/ inheritence. See "Class and Instance Variables In Ruby".

Comments