On Sat, Oct 1, 2011 at 11:05 AM, Jeroen van Ingen
[email protected]wrote:
@Adam
I’m not talking about inheritance. I just want to get access to all
ruby-classes inside a list of files in a dir and it subdirs.
This is seriously the wrong approach. It hides what’s actually
happening, is
very difficult to do correctly, and it can easily cause lots of
unrelated
code to break. I will again recommend having the class just tell the
instantiator that it exists and conforms to the expectations of the
instantiator. You could do it the way I showed or the way Adam showed.
There might be other solutions too, this is just how I handled it in the
past. But grepping files to construct a string you can evaluate is
definitely the wrong thing to do:
Problem 1: Due to its indiscriminate instantiation, your code will be
fragile and rigid ##
What happens if you have some code that should go in that directory, but
the
class shouldn’t be instantiated by your code? How will you distinguish?
What if you reopen a class, then it will get instantiated twice! You’ll
have
to go hack on the parsing code to track how many times its instantiated
each
class class MyClass; end; class MyClass; end
What happens if you need to open a class that it shouldn’t instantiate?
class String; end
That’s fine to do, but all of a sudden you can’t do
it
because your other code is going to find it.
What if your class needs to use a subclass in order to do its job class Outer; class Inner; end; end
Whoops, your code didn’t instantiate Outer
like it was supposed to, it instantiated Inner instead, which it was not
supposed to, and there is no way to fix it other than go hack on or add
special rules to the instantiator, which might in turn break its
behaviour
with the other files it reads.
What happens if you need to put the code somewhere else, but it should
be
instantiated by your instantiator?
What happens when your coworker is reading the code going “now how the
fuck
did this class become part of that list?” (in Python terms: explicit is
better than implicit)
Problem 2: You need to write a Ruby parser and traverse ASTs to do
this
right ##
What happens if you need to define a class like this MyClass = Class.new
?
Will your parser be smart enough to see it?
What about like this Object.const_set 'MyClass', Class.new
What about like this my_class = Class.new
you won’t even be able to
access
that class, how will you instantiate it?
What about like this class << obj; end