# BaseFactory -- problem in reusable metaprogramming

**URL:** <https://www.ruby-forum.com/t/basefactory-problem-in-reusable-metaprogramming/73121>\
**Category:** Ruby\
**Created:** [October 21, 2006, 3:45pm UTC](https://www.ruby-forum.com/t/basefactory-problem-in-reusable-metaprogramming/73121 "2006-10-21T15:45:31Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Trans](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/dfb087/32.png) [@Trans](https://www.ruby-forum.com/u/Trans)\
**Post date:** [October 21, 2006, 3:45pm UTC](https://www.ruby-forum.com/t/basefactory-problem-in-reusable-metaprogramming/73121/1 "2006-10-21T15:45:31Z")

</div>

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.
