From: nobu.nokada@... Date: 2005-04-12T08:32:27+09:00 Subject: Re: Factory design Hi, At Tue, 12 Apr 2005 06:56:09 +0900, Claus Spitzer wrote in [ruby-talk:137841]: > A friend of mine has recently started using Ruby, and has run into a > little problem. He is trying to create different objects depending on > the contents of a string. His intuition is to use factory design for > this, and he'd like to know if there is a Ruby Way to do this. I remember that I'd written this library and posted somewhere once. module Factory def factory(c = Proc.new) (@__factory ||= []) << c end def create(*args) n = args.size @__factory.reverse_each do |f| next if (a = f.arity) < 0 ? n < ~a : n != a return f if f = f.call(*args) end if defined?(@__factory) nil end def inherited(klass) factory(klass.method(:create)) super(klass) end end if $0 == __FILE__ class A extend Factory def initialize(obj) @obj = obj end factory(method(:new)) end class B < A factory do |obj| new(obj) if obj.respond_to?(:split) end end class B1 < B factory do |obj| new(obj) if obj.respond_to?(:string) end end class C < A factory do |obj| new(obj) if obj.respond_to?(:readline) end end p A.create("") require 'stringio' s = StringIO.new p A.create(s) p B.create(s) end -- Nobu Nakada