Module: Archive2s::ClassMethods

Defined in:
lib/archive_2s.rb,
lib/archive_2s.rb

Instance Method Summary collapse

Instance Method Details

#archive_2s(args = {}) ⇒ Object



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
# File 'lib/archive_2s.rb', line 8

def archive_2s(args = {})
  # don't allow multiple calls
  return if self.included_modules.include?(Archive2s::InstanceMethods)

  include InstanceMethods
  extend  ClassMethods

  singleton = class << self; self; end
  singleton.module_eval do
    define_method(:archive_2s_args) do
      @archive_2s_args
    end
    define_method(:archive_2s_args=) do |value|
      @archive_2s_args = value
    end
  end
  self.archive_2s_args = Archive2s::DEFAULT_ARGUMENTS.merge(args)

  #TODO: make some proxy magic so if one calls a relationship if can search the archive too
  if self.archive_2s_args[:include_by_default]
    singleton.module_eval do
      def find(*args)
        self.find_with_archived(*args)
      end
    end
  end
end

#find_archived(*ids) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/archive_2s.rb', line 55

def find_archived(*ids)
  ids.flatten!
  #don't use scopes so it is rails 2 and 3 compliant
  archived_models = ::Archive2s::Model.all(:conditions => ["model_type = ? AND model_id IN (#{(['?'] * ids.length).join(',')})", self.to_s, *ids]).collect(&:model)

  if archived_models.length != ids.length
    if ids.length == 1
      raise ActiveRecord::RecordNotFound, "Couldn't find Archived #{self.to_s} with ID=#{ids.first}"
    else
      raise ActiveRecord::RecordNotFound, "Couldn't find all Archived #{self.to_s.pluralize} with IDs (#{ids.join(',')})"
    end
  end

  #TODO: use wants
  if archived_models.length > 1
    archived_models
  else
    archived_models.first
  end
end

#find_with_archived(*args) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/archive_2s.rb', line 76

def find_with_archived(*args)
  begin
    #might as well try AR first
    super.find(*args)
  rescue Exception => e
    #can only fetch archived by ids so don't attempt if there were extra args
    if args.flatten! && args.length != args.select{|i| i == i.to_i}.length
      raise e
    else
      items = self.all(:conditions => ["id IN (#{(['?'] * args.length).join(',')})", *args])
      items += [self.find_archived(*args - items.collect(&:id))].flatten
      if args.length == items.length
        items
      else
        raise e
      end
    end
  end
end