Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add save callback to a single ActiveRecord instance, is it possible?

Is it possible to add a callback to a single ActiveRecord instance? As a further constraint this is to go on a library so I don't have control over the class (except to monkey-patch it).

This is more or less what I want to do:

def do_something_creazy
  message = Message.new
  message.on_save_call :do_even_more_crazy_stuff
end

def do_even_more_crazy_stuff(message)
  puts "Message #{message} has been saved! Hallelujah!"
end
like image 599
pupeno Avatar asked Mar 22 '10 17:03

pupeno


1 Answers

You could do something like that by adding a callback to the object right after creating it and like you said, monkey-patching the default AR before_save method:

def do_something_ballsy
    msg = Message.new
    def msg.before_save(msg)
        puts "Message #{msg} is saved."
        # Calls before_save defined in the model
        super
    end
end
like image 199
ground5hark Avatar answered Nov 14 '22 23:11

ground5hark