Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails callback for the equivalent of "after_new"

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.

like image 904
Joe Cairns Avatar asked May 14 '10 17:05

Joe Cairns


3 Answers

You can use the after_initialize callback

# app/models/foo.rb
class Foo < ActiveRecord::Base
  after_initialize :some_call

  def some_call
    puts "Who you gonna call?"
  end
end

# rails console
> foo = Foo.new # => "Who you gonna call?"
> foo = Foo.first # => "Who you gonna call?"

Beware after_initialize is triggered every time ActiveRecord do a Foo.new (calls like new, find, first and so on) see the Rails Guide

So you probably want something like this after_initialize :some_call, :if => :new_record?

# app/models/foo.rb
class Foo < ActiveRecord::Base
  after_initialize :some_call, :if => :new_record?

  def some_call
    puts "Who you gonna call?"
  end
end

# rails console
> foo = Foo.new # => "Who you gonna call?"
> foo = Foo.first
like image 195
hdorio Avatar answered Nov 13 '22 01:11

hdorio


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.

like image 4
x1a4 Avatar answered Nov 12 '22 23:11

x1a4


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).

like image 3
Toby Hede Avatar answered Nov 12 '22 23:11

Toby Hede