module VersionedRecord::InstanceMethods
Public Instance Methods
@return just the ID integer value (not the composite id, version key)
# File lib/versioned_record.rb, line 26 def _id id[0] end
Build (but do not save) a new version of the record This allows you to use the object in forms etc After the record is saved, all previous versions will be deprecated and this record will be marked as current
@example
new_version = first_version.build_version new_version.save
# File lib/versioned_record.rb, line 70 def build_version(new_attrs = {}) new_version = self.class.new(new_version_attrs(new_attrs)).tap do |built| built.deprecate_old_versions_after_create! preserve_has_one_associations_to(built) end end
Same as create_version!
but will not raise if the record is invalid @see VersionedRecord#create_version!
# File lib/versioned_record.rb, line 54 def create_version(new_attrs = {}) create_operation do self.class.create(new_version_attrs(new_attrs)) end end
Create a new version of the existing record A new version can only be created once for a given record and subsequent versions must be created by calling create_version
! on the latest version
Attributes that are not specified here will be copied to the new version from the previous version
This method will still fire ActiveRecord
callbacks for save/create etc as per normal record creation
@example
person_v1 = Person.create(name: 'Dan') person_v2 = person_v1.create_version!(name: 'Daniel')
# File lib/versioned_record.rb, line 45 def create_version!(new_attrs = {}) create_operation do self.class.create!(new_version_attrs(new_attrs)) end end
Retrieve the current version of an object (May be itself)
# File lib/versioned_record.rb, line 91 def current_version versions.current_versions.first end
Ensure that old versions are deprecated when we save (only applies on create)
# File lib/versioned_record.rb, line 97 def deprecate_old_versions_after_create! @deprecate_old_versions_after_create = true end
Retrieve all versions of this record Can be chained with other scopes
@example Versions ordered by version number
person.versions.order(:version)
# File lib/versioned_record.rb, line 84 def versions self.class.where(id: self._id) end
Private Instance Methods
# File lib/versioned_record.rb, line 111 def create_operation self.class.transaction do yield.tap do |created| deprecate_old_versions(created) if created.persisted? end end
# File lib/versioned_record.rb, line 107 def deprecate_old_versions(current_version) versions.exclude(current_version).update_all(is_current_version: false) end
# File lib/versioned_record.rb, line 102 def new_version_attrs(new_attrs) attr_builder = AttributeBuilder.new(self) attr_builder.attributes(new_attrs) end