Forum: Ruby on Rails Overriding initialize without causing an endless loop

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Eleo (Guest)
on 2007-01-09 04:59
(Received via mailing list)
This might be more of a general Ruby question than a Rails question.

I have a model Upload, with subclasses such as Image, Video, Document,
etc; that way I could check what type of file has been uploaded and
create the relevant object, and based on what object it is, make a
thumbnail or screencap or excerpt, whatever.

What I wanted to do is something along the lines of "upload =
Upload.new(params[:upload])" within the controller, and then override
Upload's initialize method so it's something like:

def initialize(attributes)
  case attributes[:file].content_type
  when /^image/
    Image.new(attributes)
  else
    super
  end
end

The problem is that the model Image < Upload I guess inherits Upload's
initialize method, so then it checks if the uploaded file is an image
and then tries to create another Image object, which checks if it is an
image and tries to create another Image object, and so on, until the
"stack level too deep".

I can't seem to think of a way around this, unless I can somehow omit
the case part of the initialize method within subclasses.  Any ideas?
This topic is locked and can not be replied to.