Module: SoftwareHeretics::ActiveRecord::SimplyVersioned::ClassMethods

Defined in:
lib/simply_versioned.rb

Instance Method Summary collapse

Instance Method Details

#simply_versioned(options = {}) ⇒ Object

Marks this ActiveRecord model as being versioned. Calls to create or save will, in future, create a series of associated Version instances that can be accessed via the versions association.

Options: limit - specifies the number of old versions to keep (default = nil, never delete old versions) automatic - controls whether versions are created automatically (default = true, save versions) exclude - specify columns that will not be saved (default = [], save all columns)

To save the record without creating a version either set versioning_enabled to false on the model before calling save or, alternatively, use without_versioning and save the model from its block.



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
70
71
72
73
74
75
# File 'lib/simply_versioned.rb', line 36

def simply_versioned( options = {} )
  bad_keys = options.keys - [:keep,:automatic,:exclude]
  raise SimplyVersioned::BadOptions.new( bad_keys ) unless bad_keys.empty?
  
  options.reverse_merge!( {
    :keep => nil,
    :automatic => true,
    :exclude => [:updated_at, :position]
  })
  
  has_many :versions, :order => 'number DESC', :as => :versionable, :dependent => :destroy, :extend => VersionsProxyMethods

  before_save :save_new_record_status
  before_save :simply_versioned_keep_dirty_version
  after_save  :simply_versioned_create_versions
  after_save  :unset_new_record_status
                      
  cattr_accessor :simply_versioned_keep_limit
  self.simply_versioned_keep_limit = options[:keep]
  
  cattr_accessor :simply_versioned_save_by_default
  self.simply_versioned_save_by_default = options[:automatic]
  
  cattr_accessor :simply_versioned_excluded_columns
  self.simply_versioned_excluded_columns = Array( options[ :exclude ] ).map( &:to_s )
  
  class_eval do
    def versioning_enabled=( enabled )
      self.instance_variable_set( :@simply_versioned_enabled, enabled )
    end
    
    def versioning_enabled?
      enabled = self.instance_variable_get( :@simply_versioned_enabled )
      if enabled.nil?
        enabled = self.instance_variable_set( :@simply_versioned_enabled, self.simply_versioned_save_by_default )
      end
      enabled
    end
  end
end