Sha256: 06c05faf9be0298304f4e46c933f9035f85cab90934b7c91a81bdfdb8f264048

Contents?: true

Size: 1.09 KB

Versions: 13

Compression:

Stored size: 1.09 KB

Contents

module Toy
  module Callbacks
    extend ActiveSupport::Concern
    include ActiveSupport::Callbacks

    included do
      extend ActiveModel::Callbacks
      define_model_callbacks :save, :create, :update, :destroy
    end

    module InstanceMethods
      def save(*)
        run_callbacks(:save) { super }
      end

      def destroy
        run_callbacks(:destroy) { super }
      end

      def run_callbacks(callback, &block)
        callback = :create if callback == :update && !persisted?

        embedded_records = self.class.embedded_lists.keys.inject([]) do |records, key|
          records += send(key).target
        end

        block = embedded_records.inject(block) do |chain, record|
          if record.class.respond_to?("_#{callback}_callbacks")
            lambda { record.run_callbacks(callback, &chain) }
          else
            chain
          end
        end
        super callback, &block
      end

      private

        def create
          run_callbacks(:create) { super }
        end

        def update
          run_callbacks(:update) { super }
        end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
toystore-0.8.3 lib/toy/callbacks.rb
toystore-0.8.2 lib/toy/callbacks.rb
toystore-0.8.1 lib/toy/callbacks.rb
toystore-0.8.0 lib/toy/callbacks.rb
toystore-0.7.0 lib/toy/callbacks.rb
toystore-0.6.6 lib/toy/callbacks.rb
toystore-0.6.5 lib/toy/callbacks.rb
toystore-0.6.4 lib/toy/callbacks.rb
toystore-0.6.3 lib/toy/callbacks.rb
toystore-0.6.2 lib/toy/callbacks.rb
toystore-0.6.1 lib/toy/callbacks.rb
toystore-0.6 lib/toy/callbacks.rb
toystore-0.5 lib/toy/callbacks.rb