views:

134

answers:

2

Right now I cant find a way to generate a callback between lines 1 and 2 here:

f = Foo.new
f.some_call
f.save!

Is there any way to simulate what would be effectively an after_new callback? Right now I'm using after_initialize but there are potential performance problems with using that since it fires for a lot of different events.

+1  A: 

Define a constructor for Foo and do what you need to do there.

An alternate solution would be to look into using after_initialize but that may not do quite what you expect.

x1a4
+1  A: 

If this is a Active Record model, then after_initialize is the correct way to handle callbacks after object creation. The framework itself makes certain assumptions about the way objects will be created from the database. Performance should not be a concern unless you have some long-running task being triggered in the callback, in which case you probably need to rethink the strategy.

If not an AR model, you can create an initialize method in your object and place the code there.

There are a number of other callbacks available depending on want you want to do, including after_create (called when a new record is created).

Toby Hede
Hi, yeah it's active record, I'm setting some required associations prior to rendering the "new" view.
Joe Cairns