Sha256: 4e6005703f4ed9c2b7a706590092a49541b086c6e39996fa44801b1bc4f69a7f

Contents?: true

Size: 1.09 KB

Versions: 3

Compression:

Stored size: 1.09 KB

Contents

module SoftDeletion
  class Dependency
    attr_reader :record, :association_name

    def initialize(record, association_name)
      @record = record
      @association_name = association_name
    end

    def soft_delete!
      return unless can_soft_delete?

      if nullify?
        nullify_dependencies
      else
        dependencies.each(&:soft_delete!)
      end
    end

    def soft_undelete!
      return unless can_soft_delete?

      klass.with_deleted do
        dependencies.each(&:soft_undelete!)
      end
    end

    protected

    def nullify?
      association.options[:dependent] == :nullify
    end

    def nullify_dependencies
      dependencies.each do |dependency|
        dependency.update_attribute(association.primary_key_name, nil)
      end
    end

    def can_soft_delete?
      klass.instance_methods.map(&:to_sym).include?(:soft_delete!)
    end

    def klass
      association.klass
    end

    def association
      record.class.reflect_on_association(association_name.to_sym)
    end

    def dependencies
      Array.wrap(record.send(association_name.to_sym))
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
soft_deletion-0.1.2 lib/soft_deletion/dependency.rb
soft_deletion-0.1.1 lib/soft_deletion/dependency.rb
soft_deletion-0.1.0 lib/soft_deletion/dependency.rb