Module: Trashcan::ActiveRecordExt::ClassMethods

Defined in:
lib/trashcan/active_record_ext.rb

Instance Method Summary collapse

Instance Method Details

#trashable(options = {}) ⇒ Object



5
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/trashcan/active_record_ext.rb', line 5

def trashable(options = {}) 
  field = options[:field] || :trashed
  field = field.to_sym if field.is_a? String
  
  singleton_class.send :define_method, :trashable_field_name do
    field
  end
  
  send :scope, "#{trashable_field_name}", where("#{trashable_field_name} = ?", true) 
  send :scope, "not_#{trashable_field_name}", where("#{trashable_field_name} = ?", false)
  
  raise "No such field #{trashable_field_name} in the #{table_name} table" unless ActiveRecord::Base.connection.column_exists?(table_name, trashable_field_name)
  
  alias_method :force_destroy, :destroy
  
  define_method "#{trashable_field_name}?" do
    send(field)
  end
  
  define_method :destroy do |*args|
    opts = args.pop || {}
    
    force = opts[:force]
    should_force = force.respond_to?(:call) ? force.call : force  
    
    if should_force 
      force_destroy                
    else
      update_attribute(field, true)
    end  
  end
  
  define_method :restore do 
    update_attribute(field, false)
  end
  
  define_method :set_trashable_field_false do
    if new_record? and send(field).nil?
      send("#{field}=", false)
    end
  end
  
  after_initialize :set_trashable_field_false
  
end