On Mon, Apr 1, 2013 at 1:16 AM, Igor Pirnovar <lists / ruby-forum.com> wrote:

> Josh Cheek wrote in post #1103861:
> > (b/c I was going to recommend making these protected instead of private,
> > in order to avoid this issue).
> >
> > -Josh
>
> You are right, making these protected instead of private seems to be the
> best solution, unless you need to shield access to your getters and
> setters from subclasses too.


You can't hide methods from subclasses.

Super = Class.new { private; attr_accessor :a }
Sub   = Class.new Super
Sub.private_instance_methods.grep /^a=?$/ # => [:a=, :a]
Sub.instance_method(:a).owner # => Super


> Taking into account, that instance
> variables in Ruby are by design public, all this accessor encapsulation
> is rather 'non-ruby-ish', nevertheless, your suggestion deserves to be
> noticed!
>
>
It's not clear to me what you mean about variables being public.

I rarely worry about my Ruby being non-ruby-ish. In this particular case, I
want to do this because I internally want to implement my public methods by
using private data. I know I could use instance variables, but I frequently
change variable names, move things around, change implementations, etc. If
I use an ivar, I start handing nil around, or setting the wrong variable.
If I use a method, I immediately get a NoMethodError. As the Pragmatic
Programmers say, "Crash Early". Furthermore, if I use a method, I can
encapsulate access from even my own object, which would allow for swapping
implementations out (e.g. switching from attr_accessor to a Struct, which
would require updating all access points if they used ivars). I know most
Rubyists aren't as bothered by things like this, and maybe they're right,
but when I disregard these concerns, I don't feel free, I feel cavalier.

-Josh