Sha256: d45c2a03539ddc316ce58b23480799c3fc90567c93ec2f8a3fd013bac7d21729

Contents?: true

Size: 1.44 KB

Versions: 4

Compression:

Stored size: 1.44 KB

Contents

module ActiveRecord
  module Duplicate
    module Callbacks
      extend ActiveSupport::Concern

      included do
        define_callbacks :duplication, terminator: "result == false", scope: [:kind, :name]
        attr_accessor :duplication_context
      end

      def dup
        super.tap do |duplicate|
          duplicate.duplication_context = :duplicate
          duplicate.run_callbacks(:duplication)
        end
      end

      def duplicate
        self.duplication_context = :original
        self.run_callbacks(:duplication) { super }
      end

      module ClassMethods
        # Duplicated from activemodel/lib/active_model/validations/callbacks.rb
        def before_duplication(*args, &block)
          options = args.last
          
          if options.is_a?(Hash) && options[:on]
            options[:if] = Array.wrap(options[:if])
            options[:if].unshift("self.duplication_context == :#{options[:on]}")
          end
          
          set_callback(:duplication, :before, *args, &block)
        end

        def after_duplication(*args, &block)
          options = args.extract_options!
          
          options[:prepend] = true
          options[:if] = Array.wrap(options[:if])
          options[:if] << "!halted"
          options[:if].unshift("self.duplication_context == :#{options[:on]}") if options[:on]
          
          set_callback(:duplication, :after, *(args << options), &block)
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
activerecord-duplicate-0.5.0 lib/activerecord-duplicate/active_record/duplicate/callbacks.rb
activerecord-duplicate-0.4.2 lib/activerecord-duplicate/active_record/duplicate/callbacks.rb
activerecord-duplicate-0.4.1 lib/active_record-duplicate/active_record/duplicate/callbacks.rb
activerecord-duplicate-0.4.0 lib/active_record-duplicate/active_record/duplicate/callbacks.rb