Module: KakurenboPuti::ActiveRecordBase

Defined in:
lib/kakurenbo_puti/active_record_base.rb

Overview

Extension module of ActiveRecord::Base

Defined Under Namespace

Modules: InstanceMethods

Instance Method Summary collapse

Instance Method Details

#soft_deletable(column: :soft_destroyed_at, dependent_associations: []) ⇒ Object

Enable soft-delete.

Parameters:

  • column (Symbol) (defaults to: :soft_destroyed_at)

    name of soft-deleted date column.

  • dependent_associations (Array<Symbol>) (defaults to: [])

    names of dependency association.

Raises:

  • (StandardException)

    if Not found soft-deleted date column.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/kakurenbo_puti/active_record_base.rb', line 9

def soft_deletable(column: :soft_destroyed_at, dependent_associations: [])
  raise "`#{column}` is not defined in #{self.class.name}." unless column_names.include?(column.to_s)

  define_singleton_method(:soft_delete_column) { column }
  delegate :soft_delete_column, to: :class

  define_model_callbacks :restore
  define_model_callbacks :soft_destroy

  scope :only_soft_destroyed, -> { where.not(id: without_soft_destroyed.select(:id)) }
  scope :without_soft_destroyed, (lambda do
    dependent_associations.inject(where(soft_delete_column => nil)) do |relation, name|
      association = relation.klass.reflect_on_all_associations.find{|a| a.name == name }
      if association.klass.method_defined?(:soft_delete_column)
        relation.joins(name).merge(association.klass.without_soft_destroyed).references(name)
      else
        relation.joins(name).references(name)
      end
    end
  end)

  include InstanceMethods
end