Module: Versions::Auto

Defined in:
lib/versions/auto.rb

Overview

When you include this module into a class, it will automatically clone itself depending on the call to should_clone?

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#previous_idObject (readonly)

Returns the value of attribute previous_id.



5
6
7
# File 'lib/versions/auto.rb', line 5

def previous_id
  @previous_id
end

Class Method Details

.included(base) ⇒ Object

Raises:

  • (TypeError)


7
8
9
10
11
12
# File 'lib/versions/auto.rb', line 7

def self.included(base)
  raise TypeError.new("Missing 'number' field in table #{base.table_name}.") unless base.column_names.include?('number')
  base.before_save :prepare_save_or_clone
  base.after_save  :clear_number_counter
  base.attr_protected :number
end

Instance Method Details

#clear_number_counterObject



46
47
48
49
# File 'lib/versions/auto.rb', line 46

def clear_number_counter
  @previous_number = nil
  true
end

#clonedObject

This method provides a hook to alter values after a clone operation (just before save: no validation).



20
21
# File 'lib/versions/auto.rb', line 20

def cloned
end

#cloned?Boolean

Return true if the record was cloned just before the last save

Returns:

  • (Boolean)


24
25
26
# File 'lib/versions/auto.rb', line 24

def cloned?
  !@previous_id.nil?
end

#prepare_save_or_cloneObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/versions/auto.rb', line 28

def prepare_save_or_clone
  if new_record?
    self[:number] = 1
  elsif changed? && should_clone?
    @previous_id = self[:id]
    self[:number] = self.previous_number + 1

    self[:id] = nil
    self[:created_at] = nil
    self[:updated_at] = nil
    @new_record = true
    cloned
  else
    @previous_id = nil
  end
  true
end

#previous_numberObject



51
52
53
# File 'lib/versions/auto.rb', line 51

def previous_number
  @previous_number ||= self[:number]
end

#should_clone?Boolean

Returns:

  • (Boolean)


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

def should_clone?
  # Always clone on update
  true
end