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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
# File 'lib/mover.rb', line 24
def move_to(to_class, conditions, instance=nil)
from_class = self
add_conditions! where = '', conditions
insert = from_class.column_names & to_class.column_names
insert -= [ 'moved_at' ]
insert.collect! { |col| connection.quote_column_name(col) }
select = insert.clone
if to_class.column_names.include?('moved_at')
insert << connection.quote_column_name('moved_at')
select << connection.quote(Time.now.utc)
end
collector = lambda { |(klass, block)| block if eval(klass.to_s) == to_class }
before = (@before_move_to || []).collect(&collector).compact
after = (@after_move_to || []).collect(&collector).compact
instances =
if instance
[ instance ]
elsif before.empty? && after.empty?
[]
else
self.find(:all, :conditions => where[5..-1])
end
exec_callbacks = lambda do |callbacks|
callbacks.each do |block|
instances.each { |instance| instance.instance_eval(&block) }
end
end
transaction do
exec_callbacks.call before
connection.execute(<<-SQL)
INSERT INTO #{to_class.table_name} (#{insert.join(', ')})
SELECT #{select.join(', ')}
FROM #{from_class.table_name}
#{where}
SQL
connection.execute("DELETE FROM #{from_class.table_name} #{where}")
exec_callbacks.call after
end
end
|