Module: InvisibleRecord::Helper

Defined in:
lib/invisible_record/helper.rb

Overview

Helps other modules complete methods

Class Method Summary collapse

Class Method Details

.define_actions(klass, deleted_ts_attr:) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/invisible_record/helper.rb', line 6

def self.define_actions(klass, deleted_ts_attr:)
  klass.define_method "restore" do |*_args|
    assign_timestamp = "#{deleted_ts_attr}="
    send(assign_timestamp, nil)
  end

  klass.define_method "restore!" do |*_args|
    restore
    save!
  end

  klass.define_method "soft_delete" do |*args|
    options = args.last || {}
    options[:datetime] ||= DateTime.now
    assign_timestamp = "#{deleted_ts_attr}="
    send(assign_timestamp, options[:datetime])
  end

  klass.define_method "soft_delete!" do |*args|
    options = args.last || {}
    options[:datetime] ||= DateTime.now
    soft_delete(datetime: options[:datetime])
    save!
  end
end

.define_hidden_attributes(klass, deleted_ts_attr:) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/invisible_record/helper.rb', line 32

def self.define_hidden_attributes(klass, deleted_ts_attr:)
  klass.attribute_names.each do |attribute|
    klass.define_method attribute do |*_args|
      protected_attributes = ["id", deleted_ts_attr]
      protected_attributes.each do |protected_attr_name|
        return attributes[protected_attr_name] if attribute == protected_attr_name
      end

      if attributes[deleted_ts_attr].present?
        nil
      else
        attributes[attribute]
      end
    end

    klass.define_method "hidden_#{attribute}" do |*_args|
      attributes[attribute]
    end
  end
end