How to organize complex callbacks in Rails?

Viewed 2784

I have a Rails application, that uses callbacks a lot.. so that I have quite a few functions getting called :after_create and :after_commit in multiple models.

I wonder if the way I am doing it right now is the best.

Basically I have the following scenario:

Class Parent < ActiveRecord::Base

has_many :children


after_create :first_function 
after_commit :last_function

    def first_function
        if !self.processed?
            self.children.create(:name => "Richard The Lion Heart")
            self.processed = true
            self.save!
        end
    end

    def last_function
        if self.processed?
            if !self.processing?
                self.process
                                    self.save!
                self.processing = true
                self.save!
            end
        end
    end

end

So you can see the whole thing depends on some strange dual boolean checks because otherwise second_function is getting called every time the model is being updated and it can be updated by the function itself and so the function is getting called repetitively.

Overall it leads me to the case where I have to introduce a new boolean check for every callback to fire off. It works but I don't see it as elegant. What am I missing?

1 Answers
Related