I have a Composition model which has a has_and_belongs_to_many :authors.
I need to fire a method after a composition changed its authors, although, since it involves the creation of a PDF file (with the name of the authors), I want to call this method only once, regardless of the number of authors added / removed.
Of course I can add / remove existing authors from the composition, so a before_save / after_save won't work here (somehow it recognizes new authors added to the composition, but not existing ones).
So I tried using after_add / after_remove, but the callbacks specified here will be invoked for every author item added to / removed from the composition.
Is there a way to have a method called only once for every "batch action" of adding / removing items from this kind of relationship?
Here's what a service might look like:
You would call it something like:
I got sick of remembering what args to send to my service classes, so I created a module called
ActsAs::CallingServices. When included in aclassthat wants to call services, the module provides a method calledcall_servicethat lets me do something like:Then, in the service class, I include some additional class-level data, like this:
The calling class (
FooClass, in this case) usesUpdateCompositionAuthorsService::SERVICE_DETAILSto build the appropriate arguments hash (detail omitted).I also have a method called
good_to_go?(detail omitted) that is included in my service classes, so my call method typically looks like:So, if the argument set is bad, I know right away instead of bumping into a
nilerror somewhere in the middle of my service.