On Fri, Aug 30, 2002 at 01:33:01AM +0900, William Pietri wrote:
> So one might start out with
> 
>     class LogLine
>         attr_reader :month, :day, :hour, :minute, :second, 
>                 :host, :program, :pid, :message
>         [...]
>     end
> 
> 
> But from there, I have two questions:
> 
> 1) Is it possible (or even sensible) to override LogLine.new so that it 
> returns an instance of the appropriate subclass? 

I ran into a similar situation when I wanted to initialize packages
kept on disk in a directory (modelled by PackageDir) and packages kept
in a file (modelled by PackageFile) through a call to
Package.new(path) in both cases.

PackageDir and PackageFile were separated in the first place because
the former supports #pack (returning a PackageFile instance) and the
latter supports #unpack (returning a PackageDir instance).

Here's how I did it (non relevant parts omitted):


  class Package
    def Package.new(path)
      if self == Package
        case File.ftype(path)
        when 'file'      then PackageFile.new(path)
        when 'directory' then PackageDir.new(path)
        end
      else
        log 1, "initializing a package object from #{File.expand_path(path)}"
        super(path)
      end
    end
  end

  class PackageDir < Package
    def pack
      ...
    end
  end

  class PackageFile < Package
    def unpack
      ...
    end
  end

pkg = Package.new('foodir')
pkg.type   =>  PackageDir
pkg = Package.new('foo.rpk')
pkg.type   =>  PackageFile



Hope this helps.

Massimiliano