From: Christopher Dicely Date: 2012-08-19T02:18:06+09:00 Subject: Re: accessing protected or private methods from class methods On Sat, Aug 18, 2012 at 9:27 AM, Denis Leclair wrote: > Hi Jan, > > You are quite right - my initial post was confusing in that regard. The > real problem is with the .configure() method but my question still > stands. > > In this particular example, I have a .configure() method which is only > intended to be run at object creation time in order to set up some of > the internal state of the object. Ideally, I would prefer to to setup > the interface so that it's not callable by any external code. It seems > like the only way to do this is to declare the method private and then > have my class method bypass the restriction using .send(). Is there no > cleaner way to do this? > > This factory method is just one example. There are many other cases > where it would make good sense to have a class method that can modify > the internal state of an object by calling into protected or private > methods on an object that it has a handle to. I just don't see a nice > way of doing it with Ruby. In a sense what you are asking for is self-contradictory in Ruby -- a class is an object (an instance of class Class), and its a different object than its own instances. So, when you take a method out of the public interface to hide it from "external" code, you are hiding it from class methods because they are external code as much as any other method that isn't part of the instance is. So you can't have a method that is part of an instance's public interface as far as methods on the object that is the instance's class are concerned, but not part of the public interface of the instance as far as methods on other external objects are concerned. It sounds like what you really want is: A privileged interface object (this is the role you seem to be using the class in, but there is no real reason this has to be a class and some OO design reasons why you may not want it to be), and A class whose instances provide a public interface that is used by the privileged interface object but not by most of the consumers that interact with the privileged interface object, and A class whose instance each wrap an instance of the class described previously, that provides a narrower public interface -- instances of this class are returned by the privileged interface object to consumer code.