Chris@0: # Copyright (c) 2005 Rick Olson Chris@0: # Chris@0: # Permission is hereby granted, free of charge, to any person obtaining Chris@0: # a copy of this software and associated documentation files (the Chris@0: # "Software"), to deal in the Software without restriction, including Chris@0: # without limitation the rights to use, copy, modify, merge, publish, Chris@0: # distribute, sublicense, and/or sell copies of the Software, and to Chris@0: # permit persons to whom the Software is furnished to do so, subject to Chris@0: # the following conditions: Chris@0: # Chris@0: # The above copyright notice and this permission notice shall be Chris@0: # included in all copies or substantial portions of the Software. Chris@0: # Chris@0: # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, Chris@0: # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF Chris@0: # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND Chris@0: # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE Chris@0: # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION Chris@0: # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION Chris@0: # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Chris@0: Chris@0: module ActiveRecord #:nodoc: Chris@0: module Acts #:nodoc: Chris@0: # Specify this act if you want to save a copy of the row in a versioned table. This assumes there is a Chris@0: # versioned table ready and that your model has a version field. This works with optimistic locking if the lock_version Chris@0: # column is present as well. Chris@0: # Chris@0: # The class for the versioned model is derived the first time it is seen. Therefore, if you change your database schema you have to restart Chris@0: # your container for the changes to be reflected. In development mode this usually means restarting WEBrick. Chris@0: # Chris@0: # class Page < ActiveRecord::Base Chris@0: # # assumes pages_versions table Chris@0: # acts_as_versioned Chris@0: # end Chris@0: # Chris@0: # Example: Chris@0: # Chris@0: # page = Page.create(:title => 'hello world!') Chris@0: # page.version # => 1 Chris@0: # Chris@0: # page.title = 'hello world' Chris@0: # page.save Chris@0: # page.version # => 2 Chris@0: # page.versions.size # => 2 Chris@0: # Chris@0: # page.revert_to(1) # using version number Chris@0: # page.title # => 'hello world!' Chris@0: # Chris@0: # page.revert_to(page.versions.last) # using versioned instance Chris@0: # page.title # => 'hello world' Chris@0: # Chris@0: # page.versions.earliest # efficient query to find the first version Chris@0: # page.versions.latest # efficient query to find the most recently created version Chris@0: # Chris@0: # Chris@0: # Simple Queries to page between versions Chris@0: # Chris@0: # page.versions.before(version) Chris@0: # page.versions.after(version) Chris@0: # Chris@0: # Access the previous/next versions from the versioned model itself Chris@0: # Chris@0: # version = page.versions.latest Chris@0: # version.previous # go back one version Chris@0: # version.next # go forward one version Chris@0: # Chris@0: # See ActiveRecord::Acts::Versioned::ClassMethods#acts_as_versioned for configuration options Chris@0: module Versioned Chris@0: CALLBACKS = [:set_new_version, :save_version_on_create, :save_version?, :clear_altered_attributes] Chris@0: def self.included(base) # :nodoc: Chris@0: base.extend ClassMethods Chris@0: end Chris@0: Chris@0: module ClassMethods Chris@0: # == Configuration options Chris@0: # Chris@0: # * class_name - versioned model class name (default: PageVersion in the above example) Chris@0: # * table_name - versioned model table name (default: page_versions in the above example) Chris@0: # * foreign_key - foreign key used to relate the versioned model to the original model (default: page_id in the above example) Chris@0: # * inheritance_column - name of the column to save the model's inheritance_column value for STI. (default: versioned_type) Chris@0: # * version_column - name of the column in the model that keeps the version number (default: version) Chris@0: # * sequence_name - name of the custom sequence to be used by the versioned model. Chris@0: # * limit - number of revisions to keep, defaults to unlimited Chris@0: # * if - symbol of method to check before saving a new version. If this method returns false, a new version is not saved. Chris@0: # For finer control, pass either a Proc or modify Model#version_condition_met? Chris@0: # Chris@0: # acts_as_versioned :if => Proc.new { |auction| !auction.expired? } Chris@0: # Chris@0: # or... Chris@0: # Chris@0: # class Auction Chris@0: # def version_condition_met? # totally bypasses the :if option Chris@0: # !expired? Chris@0: # end Chris@0: # end Chris@0: # Chris@0: # * if_changed - Simple way of specifying attributes that are required to be changed before saving a model. This takes Chris@0: # either a symbol or array of symbols. WARNING - This will attempt to overwrite any attribute setters you may have. Chris@0: # Use this instead if you want to write your own attribute setters (and ignore if_changed): Chris@0: # Chris@0: # def name=(new_name) Chris@0: # write_changed_attribute :name, new_name Chris@0: # end Chris@0: # Chris@0: # * extend - Lets you specify a module to be mixed in both the original and versioned models. You can also just pass a block Chris@0: # to create an anonymous mixin: Chris@0: # Chris@0: # class Auction Chris@0: # acts_as_versioned do Chris@0: # def started? Chris@0: # !started_at.nil? Chris@0: # end Chris@0: # end Chris@0: # end Chris@0: # Chris@0: # or... Chris@0: # Chris@0: # module AuctionExtension Chris@0: # def started? Chris@0: # !started_at.nil? Chris@0: # end Chris@0: # end Chris@0: # class Auction Chris@0: # acts_as_versioned :extend => AuctionExtension Chris@0: # end Chris@0: # Chris@0: # Example code: Chris@0: # Chris@0: # @auction = Auction.find(1) Chris@0: # @auction.started? Chris@0: # @auction.versions.first.started? Chris@0: # Chris@0: # == Database Schema Chris@0: # Chris@0: # The model that you're versioning needs to have a 'version' attribute. The model is versioned Chris@0: # into a table called #{model}_versions where the model name is singlular. The _versions table should Chris@0: # contain all the fields you want versioned, the same version column, and a #{model}_id foreign key field. Chris@0: # Chris@0: # A lock_version field is also accepted if your model uses Optimistic Locking. If your table uses Single Table inheritance, Chris@0: # then that field is reflected in the versioned model as 'versioned_type' by default. Chris@0: # Chris@0: # Acts_as_versioned comes prepared with the ActiveRecord::Acts::Versioned::ActMethods::ClassMethods#create_versioned_table Chris@0: # method, perfect for a migration. It will also create the version column if the main model does not already have it. Chris@0: # Chris@0: # class AddVersions < ActiveRecord::Migration Chris@0: # def self.up Chris@0: # # create_versioned_table takes the same options hash Chris@0: # # that create_table does Chris@0: # Post.create_versioned_table Chris@0: # end Chris@0: # Chris@0: # def self.down Chris@0: # Post.drop_versioned_table Chris@0: # end Chris@0: # end Chris@0: # Chris@0: # == Changing What Fields Are Versioned Chris@0: # Chris@0: # By default, acts_as_versioned will version all but these fields: Chris@0: # Chris@0: # [self.primary_key, inheritance_column, 'version', 'lock_version', versioned_inheritance_column] Chris@0: # Chris@0: # You can add or change those by modifying #non_versioned_columns. Note that this takes strings and not symbols. Chris@0: # Chris@0: # class Post < ActiveRecord::Base Chris@0: # acts_as_versioned Chris@0: # self.non_versioned_columns << 'comments_count' Chris@0: # end Chris@0: # Chris@0: def acts_as_versioned(options = {}, &extension) Chris@0: # don't allow multiple calls Chris@0: return if self.included_modules.include?(ActiveRecord::Acts::Versioned::ActMethods) Chris@0: Chris@0: send :include, ActiveRecord::Acts::Versioned::ActMethods Chris@0: Chris@0: cattr_accessor :versioned_class_name, :versioned_foreign_key, :versioned_table_name, :versioned_inheritance_column, Chris@0: :version_column, :max_version_limit, :track_altered_attributes, :version_condition, :version_sequence_name, :non_versioned_columns, Chris@0: :version_association_options Chris@0: Chris@0: # legacy Chris@0: alias_method :non_versioned_fields, :non_versioned_columns Chris@0: alias_method :non_versioned_fields=, :non_versioned_columns= Chris@0: Chris@0: class << self Chris@0: alias_method :non_versioned_fields, :non_versioned_columns Chris@0: alias_method :non_versioned_fields=, :non_versioned_columns= Chris@0: end Chris@0: Chris@0: send :attr_accessor, :altered_attributes Chris@0: Chris@0: self.versioned_class_name = options[:class_name] || "Version" Chris@0: self.versioned_foreign_key = options[:foreign_key] || self.to_s.foreign_key Chris@0: self.versioned_table_name = options[:table_name] || "#{table_name_prefix}#{base_class.name.demodulize.underscore}_versions#{table_name_suffix}" Chris@0: self.versioned_inheritance_column = options[:inheritance_column] || "versioned_#{inheritance_column}" Chris@0: self.version_column = options[:version_column] || 'version' Chris@0: self.version_sequence_name = options[:sequence_name] Chris@0: self.max_version_limit = options[:limit].to_i Chris@0: self.version_condition = options[:if] || true Chris@0: self.non_versioned_columns = [self.primary_key, inheritance_column, 'version', 'lock_version', versioned_inheritance_column] Chris@0: self.version_association_options = { Chris@0: :class_name => "#{self.to_s}::#{versioned_class_name}", Chris@0: :foreign_key => versioned_foreign_key, Chris@0: :dependent => :delete_all Chris@0: }.merge(options[:association_options] || {}) Chris@0: Chris@0: if block_given? Chris@0: extension_module_name = "#{versioned_class_name}Extension" Chris@0: silence_warnings do Chris@0: self.const_set(extension_module_name, Module.new(&extension)) Chris@0: end Chris@0: Chris@0: options[:extend] = self.const_get(extension_module_name) Chris@0: end Chris@0: Chris@0: class_eval do Chris@0: has_many :versions, version_association_options do Chris@0: # finds earliest version of this record Chris@0: def earliest Chris@0: @earliest ||= find(:first, :order => 'version') Chris@0: end Chris@0: Chris@0: # find latest version of this record Chris@0: def latest Chris@0: @latest ||= find(:first, :order => 'version desc') Chris@0: end Chris@0: end Chris@0: before_save :set_new_version Chris@0: after_create :save_version_on_create Chris@0: after_update :save_version Chris@0: after_save :clear_old_versions Chris@0: after_save :clear_altered_attributes Chris@0: Chris@0: unless options[:if_changed].nil? Chris@0: self.track_altered_attributes = true Chris@0: options[:if_changed] = [options[:if_changed]] unless options[:if_changed].is_a?(Array) Chris@0: options[:if_changed].each do |attr_name| Chris@0: define_method("#{attr_name}=") do |value| Chris@0: write_changed_attribute attr_name, value Chris@0: end Chris@0: end Chris@0: end Chris@0: Chris@0: include options[:extend] if options[:extend].is_a?(Module) Chris@0: end Chris@0: Chris@0: # create the dynamic versioned model Chris@0: const_set(versioned_class_name, Class.new(ActiveRecord::Base)).class_eval do Chris@0: def self.reloadable? ; false ; end Chris@0: # find first version before the given version Chris@0: def self.before(version) Chris@0: find :first, :order => 'version desc', Chris@0: :conditions => ["#{original_class.versioned_foreign_key} = ? and version < ?", version.send(original_class.versioned_foreign_key), version.version] Chris@0: end Chris@0: Chris@0: # find first version after the given version. Chris@0: def self.after(version) Chris@0: find :first, :order => 'version', Chris@0: :conditions => ["#{original_class.versioned_foreign_key} = ? and version > ?", version.send(original_class.versioned_foreign_key), version.version] Chris@0: end Chris@0: Chris@0: def previous Chris@0: self.class.before(self) Chris@0: end Chris@0: Chris@0: def next Chris@0: self.class.after(self) Chris@0: end Chris@0: Chris@0: def versions_count Chris@0: page.version Chris@0: end Chris@0: end Chris@0: Chris@0: versioned_class.cattr_accessor :original_class Chris@0: versioned_class.original_class = self Chris@0: versioned_class.set_table_name versioned_table_name Chris@0: versioned_class.belongs_to self.to_s.demodulize.underscore.to_sym, Chris@0: :class_name => "::#{self.to_s}", Chris@0: :foreign_key => versioned_foreign_key Chris@0: versioned_class.send :include, options[:extend] if options[:extend].is_a?(Module) Chris@0: versioned_class.set_sequence_name version_sequence_name if version_sequence_name Chris@0: end Chris@0: end Chris@0: Chris@0: module ActMethods Chris@0: def self.included(base) # :nodoc: Chris@0: base.extend ClassMethods Chris@0: end Chris@0: Chris@0: # Finds a specific version of this record Chris@0: def find_version(version = nil) Chris@0: self.class.find_version(id, version) Chris@0: end Chris@0: Chris@0: # Saves a version of the model if applicable Chris@0: def save_version Chris@0: save_version_on_create if save_version? Chris@0: end Chris@0: Chris@0: # Saves a version of the model in the versioned table. This is called in the after_save callback by default Chris@0: def save_version_on_create Chris@0: rev = self.class.versioned_class.new Chris@0: self.clone_versioned_model(self, rev) Chris@0: rev.version = send(self.class.version_column) Chris@0: rev.send("#{self.class.versioned_foreign_key}=", self.id) Chris@0: rev.save Chris@0: end Chris@0: Chris@0: # Clears old revisions if a limit is set with the :limit option in acts_as_versioned. Chris@0: # Override this method to set your own criteria for clearing old versions. Chris@0: def clear_old_versions Chris@0: return if self.class.max_version_limit == 0 Chris@0: excess_baggage = send(self.class.version_column).to_i - self.class.max_version_limit Chris@0: if excess_baggage > 0 Chris@0: sql = "DELETE FROM #{self.class.versioned_table_name} WHERE version <= #{excess_baggage} AND #{self.class.versioned_foreign_key} = #{self.id}" Chris@0: self.class.versioned_class.connection.execute sql Chris@0: end Chris@0: end Chris@0: Chris@0: def versions_count Chris@0: version Chris@0: end Chris@0: Chris@0: # Reverts a model to a given version. Takes either a version number or an instance of the versioned model Chris@0: def revert_to(version) Chris@0: if version.is_a?(self.class.versioned_class) Chris@0: return false unless version.send(self.class.versioned_foreign_key) == self.id and !version.new_record? Chris@0: else Chris@0: return false unless version = versions.find_by_version(version) Chris@0: end Chris@0: self.clone_versioned_model(version, self) Chris@0: self.send("#{self.class.version_column}=", version.version) Chris@0: true Chris@0: end Chris@0: Chris@0: # Reverts a model to a given version and saves the model. Chris@0: # Takes either a version number or an instance of the versioned model Chris@0: def revert_to!(version) Chris@0: revert_to(version) ? save_without_revision : false Chris@0: end Chris@0: Chris@0: # Temporarily turns off Optimistic Locking while saving. Used when reverting so that a new version is not created. Chris@0: def save_without_revision Chris@0: save_without_revision! Chris@0: true Chris@0: rescue Chris@0: false Chris@0: end Chris@0: Chris@0: def save_without_revision! Chris@0: without_locking do Chris@0: without_revision do Chris@0: save! Chris@0: end Chris@0: end Chris@0: end Chris@0: Chris@0: # Returns an array of attribute keys that are versioned. See non_versioned_columns Chris@0: def versioned_attributes Chris@0: self.attributes.keys.select { |k| !self.class.non_versioned_columns.include?(k) } Chris@0: end Chris@0: Chris@0: # If called with no parameters, gets whether the current model has changed and needs to be versioned. Chris@0: # If called with a single parameter, gets whether the parameter has changed. Chris@0: def changed?(attr_name = nil) Chris@0: attr_name.nil? ? Chris@0: (!self.class.track_altered_attributes || (altered_attributes && altered_attributes.length > 0)) : Chris@0: (altered_attributes && altered_attributes.include?(attr_name.to_s)) Chris@0: end Chris@0: Chris@0: # keep old dirty? method Chris@0: alias_method :dirty?, :changed? Chris@0: Chris@0: # Clones a model. Used when saving a new version or reverting a model's version. Chris@0: def clone_versioned_model(orig_model, new_model) Chris@0: self.versioned_attributes.each do |key| Chris@0: new_model.send("#{key}=", orig_model.send(key)) if orig_model.has_attribute?(key) Chris@0: end Chris@0: Chris@0: if orig_model.is_a?(self.class.versioned_class) Chris@0: new_model[new_model.class.inheritance_column] = orig_model[self.class.versioned_inheritance_column] Chris@0: elsif new_model.is_a?(self.class.versioned_class) Chris@0: new_model[self.class.versioned_inheritance_column] = orig_model[orig_model.class.inheritance_column] Chris@0: end Chris@0: end Chris@0: Chris@0: # Checks whether a new version shall be saved or not. Calls version_condition_met? and changed?. Chris@0: def save_version? Chris@0: version_condition_met? && changed? Chris@0: end Chris@0: Chris@0: # Checks condition set in the :if option to check whether a revision should be created or not. Override this for Chris@0: # custom version condition checking. Chris@0: def version_condition_met? Chris@0: case Chris@0: when version_condition.is_a?(Symbol) Chris@0: send(version_condition) Chris@0: when version_condition.respond_to?(:call) && (version_condition.arity == 1 || version_condition.arity == -1) Chris@0: version_condition.call(self) Chris@0: else Chris@0: version_condition Chris@0: end Chris@0: end Chris@0: Chris@0: # Executes the block with the versioning callbacks disabled. Chris@0: # Chris@0: # @foo.without_revision do Chris@0: # @foo.save Chris@0: # end Chris@0: # Chris@0: def without_revision(&block) Chris@0: self.class.without_revision(&block) Chris@0: end Chris@0: Chris@0: # Turns off optimistic locking for the duration of the block Chris@0: # Chris@0: # @foo.without_locking do Chris@0: # @foo.save Chris@0: # end Chris@0: # Chris@0: def without_locking(&block) Chris@0: self.class.without_locking(&block) Chris@0: end Chris@0: Chris@0: def empty_callback() end #:nodoc: Chris@0: Chris@0: protected Chris@0: # sets the new version before saving, unless you're using optimistic locking. In that case, let it take care of the version. Chris@0: def set_new_version Chris@0: self.send("#{self.class.version_column}=", self.next_version) if new_record? || (!locking_enabled? && save_version?) Chris@0: end Chris@0: Chris@0: # Gets the next available version for the current record, or 1 for a new record Chris@0: def next_version Chris@0: return 1 if new_record? Chris@0: (versions.calculate(:max, :version) || 0) + 1 Chris@0: end Chris@0: Chris@0: # clears current changed attributes. Called after save. Chris@0: def clear_altered_attributes Chris@0: self.altered_attributes = [] Chris@0: end Chris@0: Chris@0: def write_changed_attribute(attr_name, attr_value) Chris@0: # Convert to db type for comparison. Avoids failing Float<=>String comparisons. Chris@0: attr_value_for_db = self.class.columns_hash[attr_name.to_s].type_cast(attr_value) Chris@0: (self.altered_attributes ||= []) << attr_name.to_s unless self.changed?(attr_name) || self.send(attr_name) == attr_value_for_db Chris@0: write_attribute(attr_name, attr_value_for_db) Chris@0: end Chris@0: Chris@0: module ClassMethods Chris@0: # Finds a specific version of a specific row of this model Chris@0: def find_version(id, version = nil) Chris@0: return find(id) unless version Chris@0: Chris@0: conditions = ["#{versioned_foreign_key} = ? AND version = ?", id, version] Chris@0: options = { :conditions => conditions, :limit => 1 } Chris@0: Chris@0: if result = find_versions(id, options).first Chris@0: result Chris@0: else Chris@0: raise RecordNotFound, "Couldn't find #{name} with ID=#{id} and VERSION=#{version}" Chris@0: end Chris@0: end Chris@0: Chris@0: # Finds versions of a specific model. Takes an options hash like find Chris@0: def find_versions(id, options = {}) Chris@0: versioned_class.find :all, { Chris@0: :conditions => ["#{versioned_foreign_key} = ?", id], Chris@0: :order => 'version' }.merge(options) Chris@0: end Chris@0: Chris@0: # Returns an array of columns that are versioned. See non_versioned_columns Chris@0: def versioned_columns Chris@0: self.columns.select { |c| !non_versioned_columns.include?(c.name) } Chris@0: end Chris@0: Chris@0: # Returns an instance of the dynamic versioned model Chris@0: def versioned_class Chris@0: const_get versioned_class_name Chris@0: end Chris@0: Chris@0: # Rake migration task to create the versioned table using options passed to acts_as_versioned Chris@0: def create_versioned_table(create_table_options = {}) Chris@0: # create version column in main table if it does not exist Chris@0: if !self.content_columns.find { |c| %w(version lock_version).include? c.name } Chris@0: self.connection.add_column table_name, :version, :integer Chris@0: end Chris@0: Chris@0: self.connection.create_table(versioned_table_name, create_table_options) do |t| Chris@0: t.column versioned_foreign_key, :integer Chris@0: t.column :version, :integer Chris@0: end Chris@0: Chris@0: updated_col = nil Chris@0: self.versioned_columns.each do |col| Chris@0: updated_col = col if !updated_col && %(updated_at updated_on).include?(col.name) Chris@0: self.connection.add_column versioned_table_name, col.name, col.type, Chris@0: :limit => col.limit, Chris@0: :default => col.default, Chris@0: :scale => col.scale, Chris@0: :precision => col.precision Chris@0: end Chris@0: Chris@0: if type_col = self.columns_hash[inheritance_column] Chris@0: self.connection.add_column versioned_table_name, versioned_inheritance_column, type_col.type, Chris@0: :limit => type_col.limit, Chris@0: :default => type_col.default, Chris@0: :scale => type_col.scale, Chris@0: :precision => type_col.precision Chris@0: end Chris@0: Chris@0: if updated_col.nil? Chris@0: self.connection.add_column versioned_table_name, :updated_at, :timestamp Chris@0: end Chris@0: end Chris@0: Chris@0: # Rake migration task to drop the versioned table Chris@0: def drop_versioned_table Chris@0: self.connection.drop_table versioned_table_name Chris@0: end Chris@0: Chris@0: # Executes the block with the versioning callbacks disabled. Chris@0: # Chris@0: # Foo.without_revision do Chris@0: # @foo.save Chris@0: # end Chris@0: # Chris@0: def without_revision(&block) Chris@0: class_eval do Chris@0: CALLBACKS.each do |attr_name| Chris@0: alias_method "orig_#{attr_name}".to_sym, attr_name Chris@0: alias_method attr_name, :empty_callback Chris@0: end Chris@0: end Chris@0: block.call Chris@0: ensure Chris@0: class_eval do Chris@0: CALLBACKS.each do |attr_name| Chris@0: alias_method attr_name, "orig_#{attr_name}".to_sym Chris@0: end Chris@0: end Chris@0: end Chris@0: Chris@0: # Turns off optimistic locking for the duration of the block Chris@0: # Chris@0: # Foo.without_locking do Chris@0: # @foo.save Chris@0: # end Chris@0: # Chris@0: def without_locking(&block) Chris@0: current = ActiveRecord::Base.lock_optimistically Chris@0: ActiveRecord::Base.lock_optimistically = false if current Chris@0: result = block.call Chris@0: ActiveRecord::Base.lock_optimistically = true if current Chris@0: result Chris@0: end Chris@0: end Chris@0: end Chris@0: end Chris@0: end Chris@0: end Chris@0: Chris@0: ActiveRecord::Base.send :include, ActiveRecord::Acts::Versioned