You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

acts_as_versioned.rb 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. # Copyright (c) 2005 Rick Olson
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining
  4. # a copy of this software and associated documentation files (the
  5. # "Software"), to deal in the Software without restriction, including
  6. # without limitation the rights to use, copy, modify, merge, publish,
  7. # distribute, sublicense, and/or sell copies of the Software, and to
  8. # permit persons to whom the Software is furnished to do so, subject to
  9. # the following conditions:
  10. #
  11. # The above copyright notice and this permission notice shall be
  12. # included in all copies or substantial portions of the Software.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  18. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  19. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  20. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. module ActiveRecord #:nodoc:
  22. module Acts #:nodoc:
  23. # Specify this act if you want to save a copy of the row in a versioned table. This assumes there is a
  24. # versioned table ready and that your model has a version field. This works with optimistic locking if the lock_version
  25. # column is present as well.
  26. #
  27. # 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
  28. # your container for the changes to be reflected. In development mode this usually means restarting WEBrick.
  29. #
  30. # class Page < ActiveRecord::Base
  31. # # assumes pages_versions table
  32. # acts_as_versioned
  33. # end
  34. #
  35. # Example:
  36. #
  37. # page = Page.create(:title => 'hello world!')
  38. # page.version # => 1
  39. #
  40. # page.title = 'hello world'
  41. # page.save
  42. # page.version # => 2
  43. # page.versions.size # => 2
  44. #
  45. # page.revert_to(1) # using version number
  46. # page.title # => 'hello world!'
  47. #
  48. # page.revert_to(page.versions.last) # using versioned instance
  49. # page.title # => 'hello world'
  50. #
  51. # page.versions.earliest # efficient query to find the first version
  52. # page.versions.latest # efficient query to find the most recently created version
  53. #
  54. #
  55. # Simple Queries to page between versions
  56. #
  57. # page.versions.before(version)
  58. # page.versions.after(version)
  59. #
  60. # Access the previous/next versions from the versioned model itself
  61. #
  62. # version = page.versions.latest
  63. # version.previous # go back one version
  64. # version.next # go forward one version
  65. #
  66. # See ActiveRecord::Acts::Versioned::ClassMethods#acts_as_versioned for configuration options
  67. module Versioned
  68. CALLBACKS = [:set_new_version, :save_version_on_create, :save_version?, :clear_altered_attributes]
  69. def self.included(base) # :nodoc:
  70. base.extend ClassMethods
  71. end
  72. module ClassMethods
  73. # == Configuration options
  74. #
  75. # * <tt>class_name</tt> - versioned model class name (default: PageVersion in the above example)
  76. # * <tt>table_name</tt> - versioned model table name (default: page_versions in the above example)
  77. # * <tt>foreign_key</tt> - foreign key used to relate the versioned model to the original model (default: page_id in the above example)
  78. # * <tt>inheritance_column</tt> - name of the column to save the model's inheritance_column value for STI. (default: versioned_type)
  79. # * <tt>version_column</tt> - name of the column in the model that keeps the version number (default: version)
  80. # * <tt>sequence_name</tt> - name of the custom sequence to be used by the versioned model.
  81. # * <tt>limit</tt> - number of revisions to keep, defaults to unlimited
  82. # * <tt>if</tt> - symbol of method to check before saving a new version. If this method returns false, a new version is not saved.
  83. # For finer control, pass either a Proc or modify Model#version_condition_met?
  84. #
  85. # acts_as_versioned :if => Proc.new { |auction| !auction.expired? }
  86. #
  87. # or...
  88. #
  89. # class Auction
  90. # def version_condition_met? # totally bypasses the <tt>:if</tt> option
  91. # !expired?
  92. # end
  93. # end
  94. #
  95. # * <tt>if_changed</tt> - Simple way of specifying attributes that are required to be changed before saving a model. This takes
  96. # either a symbol or array of symbols. WARNING - This will attempt to overwrite any attribute setters you may have.
  97. # Use this instead if you want to write your own attribute setters (and ignore if_changed):
  98. #
  99. # def name=(new_name)
  100. # write_changed_attribute :name, new_name
  101. # end
  102. #
  103. # * <tt>extend</tt> - Lets you specify a module to be mixed in both the original and versioned models. You can also just pass a block
  104. # to create an anonymous mixin:
  105. #
  106. # class Auction
  107. # acts_as_versioned do
  108. # def started?
  109. # !started_at.nil?
  110. # end
  111. # end
  112. # end
  113. #
  114. # or...
  115. #
  116. # module AuctionExtension
  117. # def started?
  118. # !started_at.nil?
  119. # end
  120. # end
  121. # class Auction
  122. # acts_as_versioned :extend => AuctionExtension
  123. # end
  124. #
  125. # Example code:
  126. #
  127. # @auction = Auction.find(1)
  128. # @auction.started?
  129. # @auction.versions.first.started?
  130. #
  131. # == Database Schema
  132. #
  133. # The model that you're versioning needs to have a 'version' attribute. The model is versioned
  134. # into a table called #{model}_versions where the model name is singlular. The _versions table should
  135. # contain all the fields you want versioned, the same version column, and a #{model}_id foreign key field.
  136. #
  137. # A lock_version field is also accepted if your model uses Optimistic Locking. If your table uses Single Table inheritance,
  138. # then that field is reflected in the versioned model as 'versioned_type' by default.
  139. #
  140. # Acts_as_versioned comes prepared with the ActiveRecord::Acts::Versioned::ActMethods::ClassMethods#create_versioned_table
  141. # method, perfect for a migration. It will also create the version column if the main model does not already have it.
  142. #
  143. # class AddVersions < ActiveRecord::Migration
  144. # def self.up
  145. # # create_versioned_table takes the same options hash
  146. # # that create_table does
  147. # Post.create_versioned_table
  148. # end
  149. #
  150. # def self.down
  151. # Post.drop_versioned_table
  152. # end
  153. # end
  154. #
  155. # == Changing What Fields Are Versioned
  156. #
  157. # By default, acts_as_versioned will version all but these fields:
  158. #
  159. # [self.primary_key, inheritance_column, 'version', 'lock_version', versioned_inheritance_column]
  160. #
  161. # You can add or change those by modifying #non_versioned_columns. Note that this takes strings and not symbols.
  162. #
  163. # class Post < ActiveRecord::Base
  164. # acts_as_versioned
  165. # self.non_versioned_columns << 'comments_count'
  166. # end
  167. #
  168. def acts_as_versioned(options = {}, &extension)
  169. # don't allow multiple calls
  170. return if self.included_modules.include?(ActiveRecord::Acts::Versioned::ActMethods)
  171. send :include, ActiveRecord::Acts::Versioned::ActMethods
  172. cattr_accessor :versioned_class_name, :versioned_foreign_key, :versioned_table_name, :versioned_inheritance_column,
  173. :version_column, :max_version_limit, :track_altered_attributes, :version_condition, :version_sequence_name, :non_versioned_columns,
  174. :version_association_options
  175. # legacy
  176. alias_method :non_versioned_fields, :non_versioned_columns
  177. alias_method :non_versioned_fields=, :non_versioned_columns=
  178. class << self
  179. alias_method :non_versioned_fields, :non_versioned_columns
  180. alias_method :non_versioned_fields=, :non_versioned_columns=
  181. end
  182. send :attr_accessor, :altered_attributes
  183. self.versioned_class_name = options[:class_name] || "Version"
  184. self.versioned_foreign_key = options[:foreign_key] || self.to_s.foreign_key
  185. self.versioned_table_name = options[:table_name] || "#{table_name_prefix}#{base_class.name.demodulize.underscore}_versions#{table_name_suffix}"
  186. self.versioned_inheritance_column = options[:inheritance_column] || "versioned_#{inheritance_column}"
  187. self.version_column = options[:version_column] || 'version'
  188. self.version_sequence_name = options[:sequence_name]
  189. self.max_version_limit = options[:limit].to_i
  190. self.version_condition = options[:if] || true
  191. self.non_versioned_columns = [self.primary_key, inheritance_column, 'version', 'lock_version', versioned_inheritance_column]
  192. self.version_association_options = {
  193. :class_name => "#{self.to_s}::#{versioned_class_name}",
  194. :foreign_key => versioned_foreign_key,
  195. :dependent => :delete_all
  196. }.merge(options[:association_options] || {})
  197. if block_given?
  198. extension_module_name = "#{versioned_class_name}Extension"
  199. silence_warnings do
  200. self.const_set(extension_module_name, Module.new(&extension))
  201. end
  202. options[:extend] = self.const_get(extension_module_name)
  203. end
  204. class_eval do
  205. has_many :versions, version_association_options do
  206. # finds earliest version of this record
  207. def earliest
  208. @earliest ||= order('version').first
  209. end
  210. # find latest version of this record
  211. def latest
  212. @latest ||= order('version desc').first
  213. end
  214. end
  215. before_save :set_new_version
  216. after_create :save_version_on_create
  217. after_update :save_version
  218. after_save :clear_old_versions
  219. after_save :clear_altered_attributes
  220. unless options[:if_changed].nil?
  221. self.track_altered_attributes = true
  222. options[:if_changed] = [options[:if_changed]] unless options[:if_changed].is_a?(Array)
  223. options[:if_changed].each do |attr_name|
  224. define_method("#{attr_name}=") do |value|
  225. write_changed_attribute attr_name, value
  226. end
  227. end
  228. end
  229. include options[:extend] if options[:extend].is_a?(Module)
  230. end
  231. # create the dynamic versioned model
  232. const_set(versioned_class_name, Class.new(ActiveRecord::Base)).class_eval do
  233. def self.reloadable? ; false ; end
  234. # find first version before the given version
  235. def self.before(version)
  236. order('version desc').
  237. where("#{original_class.versioned_foreign_key} = ? and version < ?", version.send(original_class.versioned_foreign_key), version.version).
  238. first
  239. end
  240. # find first version after the given version.
  241. def self.after(version)
  242. order('version').
  243. where("#{original_class.versioned_foreign_key} = ? and version > ?", version.send(original_class.versioned_foreign_key), version.version).
  244. first
  245. end
  246. def previous
  247. self.class.before(self)
  248. end
  249. def next
  250. self.class.after(self)
  251. end
  252. def versions_count
  253. page.version
  254. end
  255. end
  256. versioned_class.cattr_accessor :original_class
  257. versioned_class.original_class = self
  258. versioned_class.table_name = versioned_table_name
  259. versioned_class.belongs_to self.to_s.demodulize.underscore.to_sym,
  260. :class_name => "::#{self.to_s}",
  261. :foreign_key => versioned_foreign_key
  262. versioned_class.send :include, options[:extend] if options[:extend].is_a?(Module)
  263. versioned_class.set_sequence_name version_sequence_name if version_sequence_name
  264. end
  265. end
  266. module ActMethods
  267. def self.included(base) # :nodoc:
  268. base.extend ClassMethods
  269. end
  270. # Finds a specific version of this record
  271. def find_version(version = nil)
  272. self.class.find_version(id, version)
  273. end
  274. # Saves a version of the model if applicable
  275. def save_version
  276. save_version_on_create if save_version?
  277. end
  278. # Saves a version of the model in the versioned table. This is called in the after_save callback by default
  279. def save_version_on_create
  280. rev = self.class.versioned_class.new
  281. self.clone_versioned_model(self, rev)
  282. rev.version = send(self.class.version_column)
  283. rev.send("#{self.class.versioned_foreign_key}=", self.id)
  284. rev.save
  285. end
  286. # Clears old revisions if a limit is set with the :limit option in <tt>acts_as_versioned</tt>.
  287. # Override this method to set your own criteria for clearing old versions.
  288. def clear_old_versions
  289. return if self.class.max_version_limit == 0
  290. excess_baggage = send(self.class.version_column).to_i - self.class.max_version_limit
  291. if excess_baggage > 0
  292. sql = "DELETE FROM #{self.class.versioned_table_name} WHERE version <= #{excess_baggage} AND #{self.class.versioned_foreign_key} = #{self.id}"
  293. self.class.versioned_class.connection.execute sql
  294. end
  295. end
  296. def versions_count
  297. version
  298. end
  299. # Reverts a model to a given version. Takes either a version number or an instance of the versioned model
  300. def revert_to(version)
  301. if version.is_a?(self.class.versioned_class)
  302. return false unless version.send(self.class.versioned_foreign_key) == self.id and !version.new_record?
  303. else
  304. return false unless version = versions.find_by_version(version)
  305. end
  306. self.clone_versioned_model(version, self)
  307. self.send("#{self.class.version_column}=", version.version)
  308. true
  309. end
  310. # Reverts a model to a given version and saves the model.
  311. # Takes either a version number or an instance of the versioned model
  312. def revert_to!(version)
  313. revert_to(version) ? save_without_revision : false
  314. end
  315. # Temporarily turns off Optimistic Locking while saving. Used when reverting so that a new version is not created.
  316. def save_without_revision
  317. save_without_revision!
  318. true
  319. rescue
  320. false
  321. end
  322. def save_without_revision!
  323. without_locking do
  324. without_revision do
  325. save!
  326. end
  327. end
  328. end
  329. # Returns an array of attribute keys that are versioned. See non_versioned_columns
  330. def versioned_attributes
  331. self.attributes.keys.select { |k| !self.class.non_versioned_columns.include?(k) }
  332. end
  333. # If called with no parameters, gets whether the current model has changed and needs to be versioned.
  334. # If called with a single parameter, gets whether the parameter has changed.
  335. def changed?(attr_name = nil)
  336. attr_name.nil? ?
  337. (!self.class.track_altered_attributes || (altered_attributes && altered_attributes.length > 0)) :
  338. (altered_attributes && altered_attributes.include?(attr_name.to_s))
  339. end
  340. # keep old dirty? method
  341. alias_method :dirty?, :changed?
  342. # Clones a model. Used when saving a new version or reverting a model's version.
  343. def clone_versioned_model(orig_model, new_model)
  344. self.versioned_attributes.each do |key|
  345. new_model.send("#{key}=", orig_model.send(key)) if orig_model.respond_to?(key)
  346. end
  347. if self.class.columns_hash.include?(self.class.inheritance_column)
  348. if orig_model.is_a?(self.class.versioned_class)
  349. new_model[new_model.class.inheritance_column] = orig_model[self.class.versioned_inheritance_column]
  350. elsif new_model.is_a?(self.class.versioned_class)
  351. new_model[self.class.versioned_inheritance_column] = orig_model[orig_model.class.inheritance_column]
  352. end
  353. end
  354. end
  355. # Checks whether a new version shall be saved or not. Calls <tt>version_condition_met?</tt> and <tt>changed?</tt>.
  356. def save_version?
  357. version_condition_met? && changed?
  358. end
  359. # Checks condition set in the :if option to check whether a revision should be created or not. Override this for
  360. # custom version condition checking.
  361. def version_condition_met?
  362. case
  363. when version_condition.is_a?(Symbol)
  364. send(version_condition)
  365. when version_condition.respond_to?(:call) && (version_condition.arity == 1 || version_condition.arity == -1)
  366. version_condition.call(self)
  367. else
  368. version_condition
  369. end
  370. end
  371. # Executes the block with the versioning callbacks disabled.
  372. #
  373. # @foo.without_revision do
  374. # @foo.save
  375. # end
  376. #
  377. def without_revision(&block)
  378. self.class.without_revision(&block)
  379. end
  380. # Turns off optimistic locking for the duration of the block
  381. #
  382. # @foo.without_locking do
  383. # @foo.save
  384. # end
  385. #
  386. def without_locking(&block)
  387. self.class.without_locking(&block)
  388. end
  389. def empty_callback() end #:nodoc:
  390. protected
  391. # sets the new version before saving, unless you're using optimistic locking. In that case, let it take care of the version.
  392. def set_new_version
  393. self.send("#{self.class.version_column}=", self.next_version) if new_record? || (!locking_enabled? && save_version?)
  394. end
  395. # Gets the next available version for the current record, or 1 for a new record
  396. def next_version
  397. return 1 if new_record?
  398. (versions.maximum('version') || 0) + 1
  399. end
  400. # clears current changed attributes. Called after save.
  401. def clear_altered_attributes
  402. self.altered_attributes = []
  403. end
  404. def write_changed_attribute(attr_name, attr_value)
  405. # Convert to db type for comparison. Avoids failing Float<=>String comparisons.
  406. attr_value_for_db = self.class.columns_hash[attr_name.to_s].type_cast_from_database(attr_value)
  407. (self.altered_attributes ||= []) << attr_name.to_s unless self.changed?(attr_name) || self.send(attr_name) == attr_value_for_db
  408. write_attribute(attr_name, attr_value_for_db)
  409. end
  410. module ClassMethods
  411. # Finds a specific version of a specific row of this model
  412. def find_version(id, version = nil)
  413. return find(id) unless version
  414. conditions = ["#{versioned_foreign_key} = ? AND version = ?", id, version]
  415. options = { :conditions => conditions, :limit => 1 }
  416. if result = find_versions(id, options).first
  417. result
  418. else
  419. raise RecordNotFound, "Couldn't find #{name} with ID=#{id} and VERSION=#{version}"
  420. end
  421. end
  422. # Finds versions of a specific model. Takes an options hash like <tt>find</tt>
  423. def find_versions(id, options = {})
  424. versioned_class.all({
  425. :conditions => ["#{versioned_foreign_key} = ?", id],
  426. :order => 'version' }.merge(options))
  427. end
  428. # Returns an array of columns that are versioned. See non_versioned_columns
  429. def versioned_columns
  430. self.columns.select { |c| !non_versioned_columns.include?(c.name) }
  431. end
  432. # Returns an instance of the dynamic versioned model
  433. def versioned_class
  434. const_get versioned_class_name
  435. end
  436. # Rake migration task to create the versioned table using options passed to acts_as_versioned
  437. def create_versioned_table(create_table_options = {})
  438. # create version column in main table if it does not exist
  439. if !self.content_columns.find { |c| %w(version lock_version).include? c.name }
  440. self.connection.add_column table_name, :version, :integer
  441. end
  442. self.connection.create_table(versioned_table_name, create_table_options) do |t|
  443. t.column versioned_foreign_key, :integer
  444. t.column :version, :integer
  445. end
  446. updated_col = nil
  447. self.versioned_columns.each do |col|
  448. updated_col = col if !updated_col && %(updated_at updated_on).include?(col.name)
  449. self.connection.add_column versioned_table_name, col.name, col.type,
  450. :limit => col.limit,
  451. :default => col.default,
  452. :scale => col.scale,
  453. :precision => col.precision
  454. end
  455. if type_col = self.columns_hash[inheritance_column]
  456. self.connection.add_column versioned_table_name, versioned_inheritance_column, type_col.type,
  457. :limit => type_col.limit,
  458. :default => type_col.default,
  459. :scale => type_col.scale,
  460. :precision => type_col.precision
  461. end
  462. if updated_col.nil?
  463. self.connection.add_column versioned_table_name, :updated_at, :timestamp
  464. end
  465. end
  466. # Rake migration task to drop the versioned table
  467. def drop_versioned_table
  468. self.connection.drop_table versioned_table_name
  469. end
  470. # Executes the block with the versioning callbacks disabled.
  471. #
  472. # Foo.without_revision do
  473. # @foo.save
  474. # end
  475. #
  476. def without_revision(&block)
  477. class_eval do
  478. CALLBACKS.each do |attr_name|
  479. alias_method "orig_#{attr_name}".to_sym, attr_name
  480. alias_method attr_name, :empty_callback
  481. end
  482. end
  483. block.call
  484. ensure
  485. class_eval do
  486. CALLBACKS.each do |attr_name|
  487. alias_method attr_name, "orig_#{attr_name}".to_sym
  488. end
  489. end
  490. end
  491. # Turns off optimistic locking for the duration of the block
  492. #
  493. # Foo.without_locking do
  494. # @foo.save
  495. # end
  496. #
  497. def without_locking(&block)
  498. current = ActiveRecord::Base.lock_optimistically
  499. ActiveRecord::Base.lock_optimistically = false if current
  500. result = block.call
  501. ActiveRecord::Base.lock_optimistically = true if current
  502. result
  503. end
  504. end
  505. end
  506. end
  507. end
  508. end
  509. ActiveRecord::Base.send :include, ActiveRecord::Acts::Versioned