has_history 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in has_history.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2012 Zimmer, Andras
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,61 @@
1
+ # HasHistory
2
+
3
+ This gem adds a simple but effective changes history to your ActiveRecord models. It is compatible with Rails but can be used without as well.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ gem 'has_history'
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install has_history
18
+
19
+ ## Usage
20
+
21
+ First you have to set up `has_history`:
22
+
23
+ $ rails g has_history:install
24
+
25
+ and then migrate your database (`rake db:migrate`).
26
+
27
+ From then on whenever you add `has_history` to your ActiveRecord model like this:
28
+
29
+ class MyModel < ActiveRecord::Base
30
+ ...
31
+ has_history
32
+ ...
33
+ end
34
+
35
+ An then you 'magically' have history for the changes. You can access history via
36
+
37
+ MyModel.history_entries
38
+
39
+ Each entry has a `modifications` attribute that contains the changes in array of hashes:
40
+
41
+ [{ attribute1 => {:before => value1_before, :after => value1_after} }, ..., { attributeN => {:before => valueN_before, :after => valueN_after} }]
42
+
43
+ ## Configuration
44
+
45
+ `has_history` has a few options to control its behavior.
46
+
47
+ - `ignore_attributes` controls which attributes are *not* included in the history tracking
48
+ - `updater_id` sets to user who made the changes (it can be taken from the record or via some other method)
49
+ - `resolution_map` holds foreign key references to attributes whose value is to be materializes (that is instead of post_id it is possible to save the title of the referenced post)
50
+
51
+ For more details see `config/initializers/has_history.rb`.
52
+
53
+ Configuration has defaults, can be set through the initializer, or can be passed in on a per-model base (as params to the `has_model` method).
54
+
55
+ ## Contributing
56
+
57
+ 1. Fork it
58
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
59
+ 3. Commit your changes (`git commit -am 'Added some feature'`)
60
+ 4. Push to the branch (`git push origin my-new-feature`)
61
+ 5. Create new Pull Request
data/Rakefile ADDED
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env rake
2
+ require "bundler/gem_tasks"
3
+
4
+ require 'rake'
5
+ require 'rake/testtask'
6
+ require 'rake/rdoctask'
7
+
8
+ desc 'Default: run unit tests.'
9
+ task :default => :test
10
+
11
+ desc 'Run unit tests on gem.'
12
+ Rake::TestTask.new(:test) do |t|
13
+ t.libs << 'lib'
14
+ t.libs << 'test'
15
+ t.pattern = 'test/**/*_test.rb'
16
+ t.verbose = true
17
+ end
@@ -0,0 +1,17 @@
1
+ # -*- encoding: utf-8 -*-
2
+ require File.expand_path('../lib/has_history/version', __FILE__)
3
+
4
+ Gem::Specification.new do |gem|
5
+ gem.authors = ["fastcatch"]
6
+ gem.email = ["andras.zimmer@gmail.com"]
7
+ gem.description = %q{Adds history to ActiveRecord models.}
8
+ gem.summary = %q{Add has_history to your ActiveRecord model and you'll instantly have access to the full history of changes of the record.}
9
+ gem.homepage = "https://github.com/fastcatch/has_history"
10
+
11
+ gem.files = `git ls-files`.split($\)
12
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
13
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
14
+ gem.name = "has_history"
15
+ gem.require_paths = ["lib"]
16
+ gem.version = HasHistory::VERSION
17
+ end
@@ -0,0 +1,12 @@
1
+ # encoding: utf-8
2
+ module HasHistory
3
+ class InstallGenerator < Rails::Generators::Base
4
+ desc "Copies a config initializer to config/initializers/has_history.rb"
5
+
6
+ source_root File.expand_path('../templates', __FILE__)
7
+
8
+ def copy_files
9
+ template 'has_history.rb', 'config/initializers/has_history.rb'
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,18 @@
1
+ require 'lib/has_history.rb'
2
+
3
+ # Array of attributes whose changes do not need to be saved to history
4
+ # Defaults to [:updated_at, :updater_id, :created_at, :creator_id, :updated_on, :created_on]
5
+ # HasHistory::History.ignore_attributes = [:updated_at, :updater_id, :created_at, :creator_id, :updated_on, :created_on]
6
+
7
+ # Determines the id(!) of the user who made the change
8
+ # if it is a symbol or a string, it is sent to the record (e.g. :updated_by)
9
+ # if it is a proc, it gets called with the record as a param (e.g. Proc.new{ User.current_user })
10
+ # Defaults to :updated_by
11
+ # HasHistory::History.updater_id = :updated_by
12
+
13
+ # Hash map to resolve foreign keys (in the form of :attribute_id => :value_method)
14
+ # changes in keys will save values from the referenced entity
15
+ # :value_method is sent to the referenced entity to fetch value to store
16
+ # e.g. { :user_id => :full_name, :post_id => :title
17
+ # Defaults to {}
18
+ # HasHistory::History.resolution_map = {}
@@ -0,0 +1,16 @@
1
+ module HasHistory
2
+ module ClassMethods
3
+
4
+ #
5
+ # put has_history in your model class and your changes will be saved
6
+ #
7
+ # available options: see initializer
8
+ #
9
+ def has_history(*args)
10
+ options = args.extract_options!
11
+ has_many :history_entries, :class_name => 'HistoryEntry', :as => :entity, :dependent => :destroy
12
+ after_update Proc.new{|record| HasHistory::History.create(record, options)}
13
+ end
14
+ end
15
+ ActiveRecord::Base.extend(ClassMethods)
16
+ end
@@ -0,0 +1,124 @@
1
+ module HasHistory
2
+
3
+ class History
4
+ CONFIGURABLES = [:ignore_attributes, :updater_id, :resolution_map]
5
+
6
+ if respond_to?(:class_attribute)
7
+ class_attribute *CONFIGURABLES
8
+ else
9
+ class_inheritable_accessor *CONFIGURABLES
10
+ end
11
+
12
+ self.ignore_attributes = [:updated_at, :updater_id, :created_at, :creator_id, :updated_on, :created_on]
13
+ self.updater_id = :updated_by
14
+ self.resolution_map = {}
15
+
16
+ def initialize(options = {})
17
+ @options = options
18
+ # passed in values take precedence over config values over baked-in defaults
19
+ CONFIGURABLES.each do |key|
20
+ @options[key] ||= self.send( key)
21
+ end
22
+ end
23
+
24
+ # Creates a new history entry (if needed)
25
+ # class method
26
+ def self.create(record, options)
27
+ history = History.new(options)
28
+ history.save(record)
29
+ end
30
+
31
+ # Check if entry has to be created and do it
32
+ def save(record)
33
+ changes = record.changes
34
+
35
+ # some values obviously change but we don't care
36
+ changes.delete_if {|key,value| @options[:ignore_attributes].include? key.to_sym}
37
+
38
+ # also remove keys for which AR reports changes but in fact there are none
39
+ changes.delete_if {|key,value| value[0]==value[1]}
40
+
41
+ # create history entry if meaningful
42
+ if !changes.empty?
43
+ HistoryEntry.create(
44
+ :entity => record,
45
+ :modified_by_id => updated_by(record),
46
+ :modifications => format_for_history(record, changes)
47
+ )
48
+ end
49
+ end
50
+
51
+ private
52
+ def format_for_history(record, changes)
53
+ # replace "*_id" references with values
54
+ formatted_changes = materialize_references(record, changes, @options[:resolution_map])
55
+
56
+ =begin
57
+ # replace time and date values with display style values
58
+ formatted_changes.each_pair do |key, values|
59
+ attribute_type = (record.send key.to_sym).class.name
60
+ if attribute_type =~ /Date|Time/
61
+ old_value = values[0].present? ? I18n.l(values[0], :locale=>locale) : ""
62
+ new_value = values[1].present? ? I18n.l(values[1], :locale=>locale) : ""
63
+ formatted_changes[key] = [old_value, new_value]
64
+ end
65
+ end
66
+
67
+ # more to come: process formatters
68
+ =end
69
+ formatted_changes.collect do |ch|
70
+ { ch[0] => {:before => ch[1][0], :after => ch[1][1]} }
71
+ end
72
+ end
73
+
74
+ def materialize_references(record, changes, mapping)
75
+ # replace "*_id" references with values with the provided mapping, leave other changes intact
76
+ changes.inject({}) do |memo, change|
77
+ resolution_attribute = mapping[change[0]] || mapping[change[0].to_sym]
78
+ cleaned = resolution_attribute ? resolve_reference(record, change, resolution_attribute) : change
79
+ memo.merge!({cleaned[0] => cleaned[1]})
80
+ end
81
+ end
82
+
83
+ def resolve_reference(record, change, resolution_attribute)
84
+ # record is an instance with the new values
85
+ # change is an array of the format [key_with_id, [old_id, new_id]]
86
+ # returns [old_value, new_value] by replacing references with resolution_attribute of the referenced entity
87
+ # => e.g. (Activity, salesrep_id => [1,2], "full_name") returns ["salesrep", ["John Past", "Jerry Comes"]]
88
+ # Please note that change should only contain one tuple!!!
89
+
90
+ key, old_id, new_id = change.flatten
91
+ attribute = key.to_s[0...-3] # remove the "_id" part
92
+
93
+ if new_id.present?
94
+ dummy_record = record.clone
95
+ dummy_record[key] = new_id
96
+ new_value = dummy_record.send(attribute.to_sym).send(resolution_attribute.to_sym)
97
+ else
98
+ new_value = nil
99
+ end
100
+
101
+ # use AR to get the old value on a dummy duplicate
102
+ if old_id.present?
103
+ dummy_record = record.clone
104
+ dummy_record[key] = old_id
105
+ old_value = dummy_record.send(attribute.to_sym).send(resolution_attribute.to_sym)
106
+ else
107
+ old_value = nil
108
+ end
109
+
110
+ result = [attribute, [old_value, new_value]]
111
+ result
112
+ end
113
+
114
+ # returns the id of the user that updated the record
115
+ def updated_by(record)
116
+ if @options[:updater_id].is_a?(Symbol) || @options[:updater_id].is_a?(String)
117
+ record.send(@options[:updater_id].to_sym)
118
+ elsif @options[:updater_id].is_a? Proc
119
+ @options[:updater_id].call(record)
120
+ end
121
+ end
122
+
123
+ end
124
+ end
@@ -0,0 +1,9 @@
1
+ class HistoryEntry < ActiveRecord::Base
2
+ belongs_to :entity, :polymorphic => true
3
+
4
+ # modifications is an array of changes, each member is of the format:
5
+ # { attribute => {:before => value_before, :after => value_after} }
6
+ serialize :modifications
7
+
8
+ validates_presence_of :entity, :modified_by_id
9
+ end
@@ -0,0 +1,3 @@
1
+ module HasHistory
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,5 @@
1
+ require File.join(File.dirname(__FILE__), 'has_history', "version")
2
+ require File.join(File.dirname(__FILE__), 'has_history', "history_entry")
3
+ require File.join(File.dirname(__FILE__), 'has_history', "ar_extension")
4
+ require File.join(File.dirname(__FILE__), 'has_history', "has_history")
5
+
@@ -0,0 +1,5 @@
1
+ class Post < ActiveRecord::Base
2
+ belongs_to :user
3
+ has_history :updater_id => Proc.new{-1}, # we don't have authentication for the test so fake it
4
+ :resolution_map => {:user_id => :name}
5
+ end
@@ -0,0 +1,3 @@
1
+ class User < ActiveRecord::Base
2
+ has_many :posts
3
+ end
data/test/db/schema.rb ADDED
@@ -0,0 +1,21 @@
1
+ ActiveRecord::Schema.define do
2
+ create_table "users", :force => true do |t|
3
+ t.column "name", :string
4
+ t.column "email", :string
5
+ end
6
+
7
+ create_table "posts", :force => true do |t|
8
+ t.column "title", :string
9
+ t.column "body", :text
10
+ t.column "user_id", :integer
11
+ end
12
+
13
+ create_table "history_entries", :force => true do |t|
14
+ t.integer "entity_id"
15
+ t.string "entity_type"
16
+ t.text "modifications"
17
+ t.integer "modified_by_id"
18
+ t.datetime "created_at"
19
+ t.datetime "updated_at"
20
+ end
21
+ end
@@ -0,0 +1,14 @@
1
+ require 'active_record'
2
+ require 'lib/has_history'
3
+ Dir['test/app/models/*.rb'].each { |f| require f }
4
+ require 'test/unit'
5
+
6
+ class ActiveSupport::TestCase
7
+
8
+ ActiveRecord::Base.establish_connection(
9
+ :adapter => "sqlite3",
10
+ :database => ":memory:"
11
+ )
12
+ load 'test/db/schema.rb'
13
+
14
+ end
@@ -0,0 +1,68 @@
1
+ require 'test_helper'
2
+
3
+ # NB: User model is not set up for has_history, the Post model is
4
+
5
+ class HasHistoryTest < ActiveSupport::TestCase
6
+
7
+ def test_ar_extension_available
8
+ assert_respond_to ActiveRecord::Base, :has_history, "ActiveRecord has_history extension is missing"
9
+ end
10
+
11
+ def test_if_models_are_valid
12
+ assert_nothing_raised { Post.new }
13
+ assert_nothing_raised { User.new }
14
+ assert_nothing_raised { HistoryEntry.new }
15
+ end
16
+
17
+ def test_no_history_case
18
+ user = User.create(:name => "Test User")
19
+ assert_not_nil user, "User not created"
20
+ user.email = "testuser@example.com"
21
+ history_count = HistoryEntry.count
22
+ assert user.save, "User not updated"
23
+ assert_equal HistoryEntry.count, history_count, "A history entry is generated when none should have been"
24
+ end
25
+
26
+ def test_base_case
27
+ history_count = HistoryEntry.count
28
+
29
+ user = User.create(:name => "Test User")
30
+ assert_not_nil user, "User not created"
31
+ post = Post.create(:title => "Test title", :body => "Test body", :user => user)
32
+ assert_not_nil post, "Post not created"
33
+ post.body = "New body"
34
+ assert post.save, "Post not updated"
35
+
36
+ assert_equal HistoryEntry.count, history_count+1, "History entry not generated"
37
+
38
+ history_entry = HistoryEntry.last
39
+ assert_equal Post.first, history_entry.entity, "History entry points to a wrong entity"
40
+ assert_equal -1, history_entry.modified_by_id, "History entry does not reference the modifier properly"
41
+
42
+ assert_equal 1, history_entry.modifications.size, "History entry modifications count is off"
43
+ modification = history_entry.modifications.first
44
+ assert modification.has_key?("body"), "History entry modifications does not contain change"
45
+ assert_equal "Test body", modification["body"][:before], "History entry modifications has a before value off"
46
+ assert_equal "New body", modification["body"][:after], "History entry modifications has an after value off"
47
+ end
48
+
49
+ def test_reference_resolution
50
+ history_count = HistoryEntry.count
51
+
52
+ user = User.create(:name => "Test User")
53
+ assert_not_nil user, "User not created"
54
+ post = Post.create(:title => "Test title", :body => "Test body", :user => user)
55
+ assert_not_nil post, "Post not created"
56
+ post.user = nil
57
+ assert post.save, "Post not updated"
58
+
59
+ assert_equal HistoryEntry.count, history_count+1, "History entry not generated"
60
+
61
+ history_entry = HistoryEntry.last
62
+ modification = history_entry.modifications.first
63
+ assert modification.has_key?("user"), "History entry modifications does not contain change"
64
+ assert_equal "Test User", modification["user"][:before], "History entry modifications has a before value off"
65
+ assert_equal nil, modification["user"][:after], "History entry modifications has an after value off"
66
+ end
67
+
68
+ end
metadata ADDED
@@ -0,0 +1,89 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: has_history
3
+ version: !ruby/object:Gem::Version
4
+ hash: 27
5
+ prerelease:
6
+ segments:
7
+ - 0
8
+ - 1
9
+ - 0
10
+ version: 0.1.0
11
+ platform: ruby
12
+ authors:
13
+ - fastcatch
14
+ autorequire:
15
+ bindir: bin
16
+ cert_chain: []
17
+
18
+ date: 2012-05-29 00:00:00 +02:00
19
+ default_executable:
20
+ dependencies: []
21
+
22
+ description: Adds history to ActiveRecord models.
23
+ email:
24
+ - andras.zimmer@gmail.com
25
+ executables: []
26
+
27
+ extensions: []
28
+
29
+ extra_rdoc_files: []
30
+
31
+ files:
32
+ - .gitignore
33
+ - Gemfile
34
+ - LICENSE
35
+ - README.md
36
+ - Rakefile
37
+ - has_history.gemspec
38
+ - lib/generators/has_history/install_generator.rb
39
+ - lib/generators/templates/has_history.rb
40
+ - lib/has_history.rb
41
+ - lib/has_history/ar_extension.rb
42
+ - lib/has_history/has_history.rb
43
+ - lib/has_history/history_entry.rb
44
+ - lib/has_history/version.rb
45
+ - test/app/models/post.rb
46
+ - test/app/models/user.rb
47
+ - test/db/schema.rb
48
+ - test/test_helper.rb
49
+ - test/unit/has_history_test.rb
50
+ has_rdoc: true
51
+ homepage: https://github.com/fastcatch/has_history
52
+ licenses: []
53
+
54
+ post_install_message:
55
+ rdoc_options: []
56
+
57
+ require_paths:
58
+ - lib
59
+ required_ruby_version: !ruby/object:Gem::Requirement
60
+ none: false
61
+ requirements:
62
+ - - ">="
63
+ - !ruby/object:Gem::Version
64
+ hash: 3
65
+ segments:
66
+ - 0
67
+ version: "0"
68
+ required_rubygems_version: !ruby/object:Gem::Requirement
69
+ none: false
70
+ requirements:
71
+ - - ">="
72
+ - !ruby/object:Gem::Version
73
+ hash: 3
74
+ segments:
75
+ - 0
76
+ version: "0"
77
+ requirements: []
78
+
79
+ rubyforge_project:
80
+ rubygems_version: 1.5.2
81
+ signing_key:
82
+ specification_version: 3
83
+ summary: Add has_history to your ActiveRecord model and you'll instantly have access to the full history of changes of the record.
84
+ test_files:
85
+ - test/app/models/post.rb
86
+ - test/app/models/user.rb
87
+ - test/db/schema.rb
88
+ - test/test_helper.rb
89
+ - test/unit/has_history_test.rb