Module: Mover::ClassMethods

Defined in:
lib/mover.rb

Instance Method Summary collapse

Instance Method Details

#after_move_to(to_class, &block) ⇒ Object



14
15
16
17
# File 'lib/mover.rb', line 14

def after_move_to(to_class, &block)
  @after_move_to ||= []
  @after_move_to << [ to_class, block ]
end

#before_move_to(to_class, &block) ⇒ Object



19
20
21
22
# File 'lib/mover.rb', line 19

def before_move_to(to_class, &block)
  @before_move_to ||= []
  @before_move_to << [ to_class, block ]
end

#move_to(to_class, conditions, instance = nil) ⇒ Object



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
  # Conditions
  add_conditions! where = '', conditions
  # Columns
  insert = from_class.column_names & to_class.column_names
  insert -= [ 'moved_at' ]
  insert.collect! { |col| connection.quote_column_name(col) }
  select = insert.clone
  # Magic columns
  if to_class.column_names.include?('moved_at')
    insert << connection.quote_column_name('moved_at')
    select << connection.quote(Time.now.utc)
  end
  # Callbacks
  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
  instances =
    if instance
      [ instance ]
    elsif before.empty? && after.empty?
      []
    else
      self.find(:all, :conditions => where[5..-1])
    end
  # Callback executor
  exec_callbacks = lambda do |callbacks|
    callbacks.each do |block|
      instances.each { |instance| instance.instance_eval(&block) }
    end
  end
  # Execute
  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

#reserve_idObject



71
72
73
74
75
76
77
78
# File 'lib/mover.rb', line 71

def reserve_id
  id = nil
  transaction do
    id = connection.insert("INSERT INTO #{self.table_name} () VALUES ()")
    connection.execute("DELETE FROM #{self.table_name} WHERE id = #{id}") if id
  end
  id
end