Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attr_accessor on class variables

Tags:

ruby

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 
like image 667
Talespin_Kit Avatar asked Jan 14 '14 19:01

Talespin_Kit


People also ask

What is attr_accessor?

attr_accessor is a shortcut method when you need both attr_reader and attr_writer . Since both reading and writing data are common, the idiomatic method attr_accessor is quite useful.

How do you create a class variable in Ruby?

Ruby Class VariablesClass variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.

What does attr_reader do in Ruby?

Summary. attr_reader and attr_writer in Ruby allow us to access and modify instance variables using the . notation by creating getter and setter methods automatically. These methods allow us to access instance variables from outside the scope of the class definition.

What is Attr_accessible?

virtual attribute – an attribute not corresponding to a column in the database. attr_accessible is used to identify attributes that are accessible by your controller methods makes a property available for mass-assignment.. It will only allow access to the attributes that you specify, denying the rest.


2 Answers

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".

like image 131
Alex.Bullard Avatar answered Oct 04 '22 21:10

Alex.Bullard


attr_accessor generates accessors for instance variables. Class variables in Ruby are a very different thing, and they are usually not what you want. What you probably want here is a class instance variable. You can use attr_accessor with class instance variables like so:

class Something   class <<self     attr_accessor :things   end end 

Then you can write Something.things = 12 and it will work.

like image 27
Chuck Avatar answered Oct 04 '22 22:10

Chuck