Only one "initialize" method allowed on AR objects?

Wes Gamble wrote:

I'm having some trouble with some seemingly basic OO stuff with one of my AR::Base descendants.

I ended up creating a custom initialize method that takes two parameters - an integer and the standard AR attributes hash, like so:

  def initialize(user_id, attributes = nil)

I think it is generally a bad idea to change the number of arguments for a method such as initialize. But if you must perhaps,

def initialize(attributes = nil, user_id = nil)    super # don't forget to init in super classes, just in case    # overwrite init here    ... end

might solve some of the problems.

In another part of my application, I was calling "clone" on one of these objects and it gave me an incorrect number of arguments error. I figured out it was because of the fact that my initialize expects 1 argument no matter what.

clone by default expects initialize without args, I think.

As soon as I provided a default value for user_id in the argument list above, the call to clone was fine - I assume since now my initialization didn't require any arguments at all.

But this is somewhat disturbing. I was under the impression that I would still have access to the regular initialize(attributes = nil) method that I get from ActiveRecord::Base. Why is it not available?

Unlike Java, both versions of initialize are the same since Ruby does not use arguments as part of the method signature.

Doesn't this imply that I can't have multiple constructors for an AR object?

Right. Again unlike Java ...

-- Long http://MeandmyCity.com/ - Free, searchable business directory for local communities http://edgesoft.ca/blog/read/2 - No-Cookie Session Support plugin for Rails