Sha256: 7ef11454e4e50199e93a176e355f6fa514e5ab81916db3f3a00ba099d4e15fdf
Contents?: true
Size: 1.82 KB
Versions: 3
Compression:
Stored size: 1.82 KB
Contents
module ComfortableMexicanSofa::HasRevisions def self.included(base) base.send :extend, ClassMethods end module ClassMethods def cms_has_revisions_for(*fields) include ComfortableMexicanSofa::HasRevisions::InstanceMethods attr_accessor :revision_data has_many :revisions, as: :record, dependent: :destroy, class_name: 'Comfy::Cms::Revision' before_save :prepare_revision after_save :create_revision define_method(:revision_fields) do fields.collect(&:to_s) end end end module InstanceMethods # Preparing revision data. A bit of a special thing to grab page blocks def prepare_revision return if self.new_record? if (self.respond_to?(:fragments_attributes_changed) && self.fragments_attributes_changed) || !(self.changed & revision_fields).empty? self.revision_data = revision_fields.inject({}) do |c, field| c[field] = self.send("#{field}_was") c end end end # Revision is created only if relevant data changed def create_revision return unless self.revision_data limit = ComfortableMexicanSofa.config.revisions_limit.to_i # creating revision if limit != 0 self.revisions.create!(data: self.revision_data) end # blowing away old revisions ids = [0] + self.revisions.order(created_at: :desc).limit(limit).pluck(:id) self.revisions.where('id NOT IN (?)', ids).destroy_all end # Assigning whatever is found in revision data and attempting to save the object def restore_from_revision(revision) return unless revision.record == self self.update_attributes!(revision.data) end end end ActiveSupport.on_load :active_record do include ComfortableMexicanSofa::HasRevisions end
Version data entries
3 entries across 3 versions & 1 rubygems