Module: ActiveReaper::ClassMethods

Defined in:
lib/active_reaper/active_reaper.rb

Instance Method Summary collapse

Instance Method Details

#reap(opts) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/active_reaper/active_reaper.rb', line 26

def reap(opts)
  unless opts[:after].respond_to?(:ago)
    raise ArgumentError.new("ActiveReaper: option for 'after' must be a FixNum (amount in seconds)")
  end
  
  unless [:delete, :destroy].include? (opts[:using] || :delete)
    raise ArgumentError.new("ActiveReaper: option for 'using' must be either :delete or :destroy")
  end
  
  unless  self.column_names.include?(opts[:determined_by].to_s) || 
          self.instance_methods.include?(opts[:determined_by]) ||
          (opts[:determined_by].nil? && self.column_names.include?('created_at'))
    raise ArgumentError.new("ActiveReaper: option for 'determined_by' must be either a table column name or an instance method.  If option is left blank, table must have a datetime 'created_at' column.")
  end
  
  unless (opts[:if].nil? && opts[:unless].nil?) || ( !!opts[:if] ^ !!opts[:unless])
    raise ArgumentError.new("ActiveReaper: Pass only 'if' or 'unless' as a condition")
  end
  
  unless self.column_names.include?(opts[:if].to_s) || (opts[:if].to_s.last=='?' && self.column_names.include?(opts[:if].to_s.chop)) || self.instance_methods.include?(opts[:if]) || opts[:if].nil?
    raise ArgumentError.new("ActiveReaper: option for 'if' or 'unless' must be either a table column name or an instance method.")
  end
  
  settings = {
    :after => opts[:after],
    :using => opts[:using] || :delete,
    :determined_by => opts[:determined_by].nil? ? :created_at : opts[:determined_by],
    :determined_by_type => self.column_names.include?(opts[:determined_by].to_s) ? :column : :method,
    :condition => opts[:if].nil? ? opts[:unless] : opts[:if],
    :condition_type => nil,
    :truth_value => nil
  }
  
  if settings[:condition]
    settings[:truth_value] = opts[:if].nil? ? false : true
    settings[:condition_type] = self.column_names.include?(settings[:condition].to_s) ? :column : :method
  end  
  
  REAPED_CLASSES[self] = settings
end