BaseFactory -- problem in reusable metaprogramming

T

Trans

I'm playing with this simple Factory pattern whereby the base class is
also the factory.

class X
class << self
alias :instance :new

# Factory-pattern initialization.

def new(type, *set, &yld)
begin
send(type, *set, &yld)
rescue
raise "Not a known #{self} -- #{type}."
end
end

# Subclasses should have standard #new methods.

def inherited( subclass )
class << subclass
alias :new :instance
end
end

end
end

# Using it...

class X
def self.y ; Y.new ; end
class Y < self
end
end

X.new:)y)

It works fine when I handle it manually like this. But when I try to
make this pattern reusable, creating a BaseFactory module to include in
X, it fails to alias correctly. Unfortunately it seems the #included
callback is invoked _after_ inclusion is finished so I don't see a way
to do it other than directly injecting the code into the class/module,
which bad OOP form to say the least. This would seem to be inconsitant
with #inherited which I think happens _before_ the actual inheritance
takes place.

It also presents an interesting question about aliasing. Since aliasing
happens at the moment of invocation, it is essentially a "copy and
paste" sort of metacommand. For a dynamic language like Ruby, might we
not make better use of a dynamic variation of alias instead? But is
such a thing possible?

T.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top