Module: Platanus::Activable

Defined in:
lib/platanus/activable.rb

Overview

When included in a model definition, this module provides soft delete capabilities via the remove method.

This module also defines a remove callback.

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



13
14
15
16
17
18
# File 'lib/platanus/activable.rb', line 13

def self.included(base)
  base.define_callbacks :remove
  base.attr_protected :removed_at
  base.send(:default_scope, base.where(:removed_at => nil))
  base.extend ClassMethods
end

Instance Method Details

#is_active?Boolean

Returns true if object hasnt been removed.

Returns:

  • (Boolean)


41
42
43
# File 'lib/platanus/activable.rb', line 41

def is_active?
  self.removed_at.nil?
end

#remove!Object

Deactivates a single record.



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/platanus/activable.rb', line 61

def remove!
  self.transaction do
    run_callbacks :remove do
      notify_observers :before_remove

      # Retrieve dependant properties and remove them.
      self.class.reflect_on_all_associations.select do |assoc|
        if assoc.options[:dependent] == :destroy
          collection = self.send(assoc.name)
          collection.remove_all if collection.respond_to? :remove_all
        end
      end

      # Use update column to prevent update callbacks from being ran.
      self.update_column(:removed_at, DateTime.now)
      notify_observers :after_remove
    end
  end
end

#replace!Object

Clones current object and then removes it.



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/platanus/activable.rb', line 46

def replace!
  # self.class.transaction do
  #   clone = self.class.new
  #   self.attributes.each do |key, value|
  #     next if ['id','created_at','removed_at'].include? key
  #     clone.send(:write_attribute, key, value)
  #   end
  #   yield
  #   clone.save!
  #   self.remove!
  #   return clone
  # end
end