A
A
Alexander Grishin2016-03-10 22:43:48
Ruby on Rails
Alexander Grishin, 2016-03-10 22:43:48

How to list the attr_accessor class?

Help me to understand in detail the following implementation of the code found on the internet:

class MyBaseClass
  def self.attr_accessor(*vars)
    @attributes ||= []
    @attributes.concat vars
    super(*vars)
  end

  def self.attributes
    @attributes
  end

  def attributes
    self.class.attributes
  end
end

class SubClass < MyBaseClass
  attr_accessor :id, :title, :body
end

SubClass.new.attributes.inspect #=> [:id, :title, :body]

This line is especially interesting @attributes ||= []

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Grudinkin, 2016-03-11
@Hunt666

About the operator ||=: assignment occurs if the variable is empty.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question