How to connect to save! with rails before_save! Call back

Is there a way to connect to save!with a callback?

I am looking for something like:

class CompositeService < Service
  attr_accessible :subservices

  before_save :save_subservices
  before_save :save_subservices! if bang_save?

  private

  def save_subservices
    @subservices.each(&:save)
  end

  def save_subservices!
    @subservices.each(&:save!)
  end
end

Where a save!cascades and calls save!in association (faux) subservices.

+4
source share
3 answers

Interesting: Is this additional logic necessary?

If the method saveon each of yours @subservicesobeys ActiveRecord semantics save, you are likely to get the right behavior for free.

In other words, be sure that the methods savereturn trueeither falsefor success or failure. Then the composite code becomes so simple:

class CompositeService < Service
  attr_accessible :subservices

  before_save :save_subservices

  private

  def save_subservices
    @subservices.all?(&:save)
  end
end

- , save_subservices false, . save save. save! .

composite.save
# => false

composite.save!
# => ActiveRecord::RecordNotSaved
+1

, , . .

, ! .

class CompositeService < Service
  before_save :some_callback

  def some_callback
    lines = caller.select { |line| line =~ /persistence.rb/ && line =~ /save!/ }

    if lines.any?
      @subservices.each(&:save!)
    else
      @subservices.each(&:save)
    end
  end
end
+2

All Articles