Reputation: 3656
I have an after save callback:
after_save :do_an_expensive_task_on_basis_of_flag_value
I later realized that this is a very expensive task and it does not make sense to call it when the value of flag is not set(on create) OR value of flag is not updated on update.
So one thing , i can do is to replace it with:
after_create :do_an_expensive_task_on_basis_of_flag_value , :if => Proc.new {|a| a.flag.present?}
after_update :do_an_expensive_task_on_basis_of_flag_value , :if => Proc.new {|a| a.flag_changed?}
But i am looking for a one liner, with a proc such that this task is called only when Flag is set on create and flag is updated on update with :after_save
.
Note: This is not correct way:
after_save :do_an_expensive_task_on_basis_of_flag_value , :if => Proc.new {|a| a.flag.present? or a.flag_changed?}
As it still calls callback on update , even when flag is not changed.
Upvotes: 2
Views: 6246
Reputation: 4367
a.flag_changed?
works for both cases. But just for your knowledge, you could do it like this:
after_save :do_an_expensive_task_on_basis_of_flag_value , :if => Proc.new {|a| (new_record? and a.flag.present?) or a.flag_changed?}
Upvotes: 4
Reputation: 25029
The logic in your proc is slightly wrong. It will always run if the flag is present, regardless of if it has been changed on this save or not.
Surely a.flag_changed?
is enough for the logic you need? If the flag is added, it will be changed from (its default value, probably nil) to (whatever you set it to).
Upvotes: 3