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
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.
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.
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.
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.
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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With