Issue #6470 has been updated by rupert (Robert Pankowecki).


> There's no use for private attr_reader, attr_writer, etc.


The intended usage is to ease future refactorings. If you always start with a method then later you can easily redefine just the method.

Initial code

~~~
class Something
  private attr_accessor :x, :y

  def something(a)
    self.x = a + y
  end
end
~~~

Code after refactoring:

~~~
class Something
  private attr_accessor :y
  private attr_reader :x

  def something(a)
    self.x = a + y
  end

  private

  def x=(new_value)
    @x_set_at = Time.now
    @x = new_value
  end
~~~


Notice that nothing setting `@x` had to be refactored because `@x` variable was always changed via the `self.x=` setter. 

So when the time comes and cache expiration or additional logic needs to be added, makes it easy to just redefine the setter or getter with additional logic.

That's why I always prefer to use private accessors instead of instance variables. They are more flexible.

----------------------------------------
Feature #6470: Make attr_accessor return the list of generated method
https://bugs.ruby-lang.org/issues/6470#change-76219

* Author: rupert (Robert Pankowecki)
* Status: Open
* Priority: Normal
* Assignee: matz (Yukihiro Matsumoto)
* Target version: 
----------------------------------------
attr_accesor currently returns nil. It would be more helpful if it return list of generated methods so that it can become an argument to other methods like :private or :protected. That way private accessors can still be defined at top of the class and be private without changing the visibility of next methods. 

class Something
  private *attr_accessor :user, :action # IMHO This is nice
  # private attr_accessor :user, :action # <-- would be even better if :private method accepted arrays

  def initialize(user, action)
    self.user   = user
    self.action = action
  end

  def public_method
    user.do_something(action)
  end
end


VS


class Something
  private; attr_accessor :user, :action; public # IMHO Hack!!

  def initialize(user, action)
    self.user   = user
    self.action = action
  end

  def public_method
    user.do_something(action)
  end
end


VS


class Something
  def initialize(user, action)
    self.user   = user
    self.action = action
  end

  def public_method
    user.do_something(action)
  end

  private
  attr_accessor :user, :action # IMHO Does not look nice at bottom of the class definition
end



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>