Merge branch 'json_column_support'. close #287

Conflicts:
	CHANGELOG.md
This commit is contained in:
Ben Atkins 2013-10-21 15:36:35 -04:00
commit 9500429b37
12 changed files with 95 additions and 61 deletions

View File

@ -2,6 +2,8 @@
- [#288](https://github.com/airblade/paper_trail/issues/288) - Change all scope declarations to class methods on the `PaperTrail::Version` - [#288](https://github.com/airblade/paper_trail/issues/288) - Change all scope declarations to class methods on the `PaperTrail::Version`
class. Fixes usability when `PaperTrail::Version.abstract_class? == true`. class. Fixes usability when `PaperTrail::Version.abstract_class? == true`.
- [#287](https://github.com/airblade/paper_trail/issues/287) - Support for
[PostgreSQL's JSON Type](http://www.postgresql.org/docs/9.2/static/datatype-json.html) for storing `object` and `object_changes`.
- [#281](https://github.com/airblade/paper_trail/issues/281) - `Rails::Controller` helper will return `false` for the - [#281](https://github.com/airblade/paper_trail/issues/281) - `Rails::Controller` helper will return `false` for the
`paper_trail_enabled_for_controller` method if `PaperTrail.enabled? == false`. `paper_trail_enabled_for_controller` method if `PaperTrail.enabled? == false`.
- [#280](https://github.com/airblade/paper_trail/pull/280) - Don't track virtual timestamp attributes. - [#280](https://github.com/airblade/paper_trail/pull/280) - Don't track virtual timestamp attributes.
@ -21,6 +23,8 @@
- [#199](https://github.com/airblade/paper_trail/pull/199) - Rails 4 compatibility. - [#199](https://github.com/airblade/paper_trail/pull/199) - Rails 4 compatibility.
- [#165](https://github.com/airblade/paper_trail/pull/165) - Namespaced the `Version` class under the `PaperTrail` module. - [#165](https://github.com/airblade/paper_trail/pull/165) - Namespaced the `Version` class under the `PaperTrail` module.
- [#119](https://github.com/airblade/paper_trail/issues/119) - Support for [Sinatra](http://www.sinatrarb.com/); decoupled gem from `Rails`. - [#119](https://github.com/airblade/paper_trail/issues/119) - Support for [Sinatra](http://www.sinatrarb.com/); decoupled gem from `Rails`.
- Renamed the default serializers from `PaperTrail::Serializers::Yaml` and `PaperTrail::Serializers::Json` to the capitalized forms,
`PaperTrail::Serializers::YAML` and `PaperTrail::Serializers::JSON`.
## 2.7.2 ## 2.7.2

View File

@ -703,7 +703,7 @@ module PaperTrail
end end
``` ```
Why would you do this? In this example, `author_id` is an attribute of `Article` and PaperTrail will store it anyway in serialized (YAML) form in the `object` column of the `version` record. But let's say you wanted to pull out all versions for a particular author; without the metadata you would have to deserialize (reify) each `version` object to see if belonged to the author in question. Clearly this is inefficient. Using the metadata you can find just those versions you want: Why would you do this? In this example, `author_id` is an attribute of `Article` and PaperTrail will store it anyway in a serialized form in the `object` column of the `version` record. But let's say you wanted to pull out all versions for a particular author; without the metadata you would have to deserialize (reify) each `version` object to see if belonged to the author in question. Clearly this is inefficient. Using the metadata you can find just those versions you want:
```ruby ```ruby
PaperTrail::Version.all(:conditions => ['author_id = ?', author_id]) PaperTrail::Version.all(:conditions => ['author_id = ?', author_id])
@ -849,7 +849,7 @@ end
## Using a custom serializer ## Using a custom serializer
By default, PaperTrail stores your changes as a YAML dump. You can override this with the serializer config option: By default, PaperTrail stores your changes as a `YAML` dump. You can override this with the serializer config option:
```ruby ```ruby
>> PaperTrail.serializer = MyCustomSerializer >> PaperTrail.serializer = MyCustomSerializer
@ -857,8 +857,8 @@ By default, PaperTrail stores your changes as a YAML dump. You can override this
A valid serializer is a `module` (or `class`) that defines a `load` and `dump` method. These serializers are included in the gem for your convenience: A valid serializer is a `module` (or `class`) that defines a `load` and `dump` method. These serializers are included in the gem for your convenience:
* [Yaml](https://github.com/airblade/paper_trail/blob/master/lib/paper_trail/serializers/yaml.rb) - Default * [YAML](https://github.com/airblade/paper_trail/blob/master/lib/paper_trail/serializers/yaml.rb) - Default
* [Json](https://github.com/airblade/paper_trail/blob/master/lib/paper_trail/serializers/json.rb) * [JSON](https://github.com/airblade/paper_trail/blob/master/lib/paper_trail/serializers/json.rb)
## Limiting the number of versions created per object instance ## Limiting the number of versions created per object instance

View File

@ -8,7 +8,7 @@ module PaperTrail
def initialize def initialize
@enabled = true # Indicates whether PaperTrail is on or off. @enabled = true # Indicates whether PaperTrail is on or off.
@timestamp_field = :created_at @timestamp_field = :created_at
@serializer = PaperTrail::Serializers::Yaml @serializer = PaperTrail::Serializers::YAML
end end
end end
end end

View File

@ -90,20 +90,30 @@ module PaperTrail
self.paper_trail_enabled_for_model = true self.paper_trail_enabled_for_model = true
end end
def paper_trail_version_class
@paper_trail_version_class ||= version_class_name.constantize
end
# Used for Version#object attribute # Used for Version#object attribute
def serialize_attributes_for_paper_trail(attributes) def serialize_attributes_for_paper_trail(attributes)
# don't serialize before values before inserting into columns of type `JSON` on `PostgreSQL` databases
return attributes if self.paper_trail_version_class.object_col_is_json?
serialized_attributes.each do |key, coder| serialized_attributes.each do |key, coder|
if attributes.key?(key) if attributes.key?(key)
coder = PaperTrail::Serializers::Yaml unless coder.respond_to?(:dump) # Fall back to YAML if `coder` has no `dump` method coder = PaperTrail::Serializers::YAML unless coder.respond_to?(:dump) # Fall back to YAML if `coder` has no `dump` method
attributes[key] = coder.dump(attributes[key]) attributes[key] = coder.dump(attributes[key])
end end
end end
end end
def unserialize_attributes_for_paper_trail(attributes) def unserialize_attributes_for_paper_trail(attributes)
# don't serialize before values before inserting into columns of type `JSON` on `PostgreSQL` databases
return attributes if self.paper_trail_version_class.object_col_is_json?
serialized_attributes.each do |key, coder| serialized_attributes.each do |key, coder|
if attributes.key?(key) if attributes.key?(key)
coder = PaperTrail::Serializers::Yaml unless coder.respond_to?(:dump) coder = PaperTrail::Serializers::YAML unless coder.respond_to?(:dump)
attributes[key] = coder.load(attributes[key]) attributes[key] = coder.load(attributes[key])
end end
end end
@ -111,9 +121,12 @@ module PaperTrail
# Used for Version#object_changes attribute # Used for Version#object_changes attribute
def serialize_attribute_changes(changes) def serialize_attribute_changes(changes)
# don't serialize before values before inserting into columns of type `JSON` on `PostgreSQL` databases
return changes if self.paper_trail_version_class.object_changes_col_is_json?
serialized_attributes.each do |key, coder| serialized_attributes.each do |key, coder|
if changes.key?(key) if changes.key?(key)
coder = PaperTrail::Serializers::Yaml unless coder.respond_to?(:dump) # Fall back to YAML if `coder` has no `dump` method coder = PaperTrail::Serializers::YAML unless coder.respond_to?(:dump) # Fall back to YAML if `coder` has no `dump` method
old_value, new_value = changes[key] old_value, new_value = changes[key]
changes[key] = [coder.dump(old_value), changes[key] = [coder.dump(old_value),
coder.dump(new_value)] coder.dump(new_value)]
@ -122,9 +135,12 @@ module PaperTrail
end end
def unserialize_attribute_changes(changes) def unserialize_attribute_changes(changes)
# don't serialize before values before inserting into columns of type `JSON` on `PostgreSQL` databases
return changes if self.paper_trail_version_class.object_changes_col_is_json?
serialized_attributes.each do |key, coder| serialized_attributes.each do |key, coder|
if changes.key?(key) if changes.key?(key)
coder = PaperTrail::Serializers::Yaml unless coder.respond_to?(:dump) coder = PaperTrail::Serializers::YAML unless coder.respond_to?(:dump)
old_value, new_value = changes[key] old_value, new_value = changes[key]
changes[key] = [coder.load(old_value), changes[key] = [coder.load(old_value),
coder.load(new_value)] coder.load(new_value)]
@ -139,12 +155,12 @@ module PaperTrail
# Returns true if this instance is the current, live one; # Returns true if this instance is the current, live one;
# returns false if this instance came from a previous version. # returns false if this instance came from a previous version.
def live? def live?
source_version.nil? @is_live ||= source_version.nil?
end end
# Returns who put the object into its current state. # Returns who put the object into its current state.
def originator def originator
version_class.with_item_keys(self.class.base_class.name, id).last.try :whodunnit @originator ||= self.class.paper_trail_version_class.with_item_keys(self.class.base_class.name, id).last.try :whodunnit
end end
# Returns the object (not a Version) as it was at the given timestamp. # Returns the object (not a Version) as it was at the given timestamp.
@ -188,10 +204,6 @@ module PaperTrail
private private
def version_class
version_class_name.constantize
end
def source_version def source_version
send self.class.version_association_name send self.class.version_association_name
end end
@ -203,8 +215,9 @@ module PaperTrail
:whodunnit => PaperTrail.whodunnit :whodunnit => PaperTrail.whodunnit
} }
if changed_notably? and version_class.column_names.include?('object_changes') if changed_notably? and self.class.paper_trail_version_class.column_names.include?('object_changes')
data[:object_changes] = PaperTrail.serializer.dump(changes_for_paper_trail) data[:object_changes] = self.class.paper_trail_version_class.object_changes_col_is_json? ? changes_for_paper_trail :
PaperTrail.serializer.dump(changes_for_paper_trail)
end end
send(self.class.versions_association_name).create! merge_metadata(data) send(self.class.versions_association_name).create! merge_metadata(data)
end end
@ -212,13 +225,15 @@ module PaperTrail
def record_update def record_update
if paper_trail_switched_on? && changed_notably? if paper_trail_switched_on? && changed_notably?
object_attrs = object_attrs_for_paper_trail(item_before_change)
data = { data = {
:event => paper_trail_event || 'update', :event => paper_trail_event || 'update',
:object => object_to_string(item_before_change), :object => self.class.paper_trail_version_class.object_col_is_json? ? object_attrs : PaperTrail.serializer.dump(object_attrs),
:whodunnit => PaperTrail.whodunnit :whodunnit => PaperTrail.whodunnit
} }
if version_class.column_names.include? 'object_changes' if self.class.paper_trail_version_class.column_names.include?('object_changes')
data[:object_changes] = PaperTrail.serializer.dump(changes_for_paper_trail) data[:object_changes] = self.class.paper_trail_version_class.object_changes_col_is_json? ? changes_for_paper_trail :
PaperTrail.serializer.dump(changes_for_paper_trail)
end end
send(self.class.versions_association_name).build merge_metadata(data) send(self.class.versions_association_name).build merge_metadata(data)
end end
@ -227,18 +242,20 @@ module PaperTrail
def changes_for_paper_trail def changes_for_paper_trail
self.changes.delete_if do |key, value| self.changes.delete_if do |key, value|
!notably_changed.include?(key) !notably_changed.include?(key)
end.tap do |changes| end.tap { |changes| self.class.serialize_attribute_changes(changes) }
self.class.serialize_attribute_changes(changes) # Use serialized value for attributes when necessary
end
end end
def record_destroy def record_destroy
if paper_trail_switched_on? and not new_record? if paper_trail_switched_on? and not new_record?
version_class.create merge_metadata(:item_id => self.id, object_attrs = object_attrs_for_paper_trail(item_before_change)
:item_type => self.class.base_class.name, data = {
:event => paper_trail_event || 'destroy', :item_id => self.id,
:object => object_to_string(item_before_change), :item_type => self.class.base_class.name,
:whodunnit => PaperTrail.whodunnit) :event => paper_trail_event || 'destroy',
:object => self.class.paper_trail_version_class.object_col_is_json? ? object_attrs : PaperTrail.serializer.dump(object_attrs),
:whodunnit => PaperTrail.whodunnit
}
self.class.paper_trail_version_class.create merge_metadata(data)
send(self.class.versions_association_name).send :load_target send(self.class.versions_association_name).send :load_target
end end
end end
@ -276,11 +293,11 @@ module PaperTrail
end end
end end
def object_to_string(object) # returns hash of object attributes (with appropriate attributes serialized), ommitting attributes to be skipped
def object_attrs_for_paper_trail(object)
_attrs = object.attributes.except(*self.paper_trail_options[:skip]).tap do |attributes| _attrs = object.attributes.except(*self.paper_trail_options[:skip]).tap do |attributes|
self.class.serialize_attributes_for_paper_trail attributes self.class.serialize_attributes_for_paper_trail(attributes)
end end
PaperTrail.serializer.dump(_attrs)
end end
def changed_notably? def changed_notably?

View File

@ -2,7 +2,7 @@ require 'active_support/json'
module PaperTrail module PaperTrail
module Serializers module Serializers
module Json module JSON
extend self # makes all instance methods become module methods as well extend self # makes all instance methods become module methods as well
def load(string) def load(string)

View File

@ -2,15 +2,15 @@ require 'yaml'
module PaperTrail module PaperTrail
module Serializers module Serializers
module Yaml module YAML
extend self # makes all instance methods become module methods as well extend self # makes all instance methods become module methods as well
def load(string) def load(string)
YAML.load string ::YAML.load string
end end
def dump(object) def dump(object)
YAML.dump object ::YAML.dump object
end end
end end
end end

View File

@ -42,6 +42,16 @@ module PaperTrail
order("#{PaperTrail.timestamp_field} ASC") order("#{PaperTrail.timestamp_field} ASC")
end end
# Returns whether the `object` column is using the `json` type supported by PostgreSQL
def self.object_col_is_json?
@object_col_is_json ||= columns_hash['object'].type == :json
end
# Returns whether the `object_changes` column is using the `json` type supported by PostgreSQL
def self.object_changes_col_is_json?
@object_changes_col_is_json ||= columns_hash['object_changes'].type == :json
end
# Restore the item from this version. # Restore the item from this version.
# #
# This will automatically restore all :has_one associations as they were "at the time", # This will automatically restore all :has_one associations as they were "at the time",
@ -59,7 +69,7 @@ module PaperTrail
options.reverse_merge! :has_one => false options.reverse_merge! :has_one => false
unless object.nil? unless object.nil?
attrs = PaperTrail.serializer.load object attrs = self.class.object_col_is_json? ? object : PaperTrail.serializer.load(object)
# Normally a polymorphic belongs_to relationship allows us # Normally a polymorphic belongs_to relationship allows us
# to get the object we belong to by calling, in this case, # to get the object we belong to by calling, in this case,
@ -112,9 +122,12 @@ module PaperTrail
def changeset def changeset
return nil unless self.class.column_names.include? 'object_changes' return nil unless self.class.column_names.include? 'object_changes'
@changeset ||= HashWithIndifferentAccess.new(PaperTrail.serializer.load(object_changes)).tap do |changes| _changes = self.class.object_changes_col_is_json? ? object_changes : PaperTrail.serializer.load(object_changes)
@changeset ||= HashWithIndifferentAccess.new(_changes).tap do |changes|
item_type.constantize.unserialize_attribute_changes(changes) item_type.constantize.unserialize_attribute_changes(changes)
end rescue {} end
rescue
{}
end end
# Returns who put the item into the state stored in this version. # Returns who put the item into the state stored in this version.

View File

@ -1,6 +1,6 @@
# This custom serializer excludes nil values # This custom serializer excludes nil values
module CustomJsonSerializer module CustomJsonSerializer
extend PaperTrail::Serializers::Json extend PaperTrail::Serializers::JSON
def self.load(string) def self.load(string)
parsed_value = super(string) parsed_value = super(string)

View File

@ -14,16 +14,16 @@ class SerializerTest < ActiveSupport::TestCase
@fluxor.update_attributes :name => 'Some more text.' @fluxor.update_attributes :name => 'Some more text.'
end end
should 'work with the default yaml serializer' do should 'work with the default `YAML` serializer' do
# Normal behaviour # Normal behaviour
assert_equal 2, @fluxor.versions.length assert_equal 2, @fluxor.versions.length
assert_nil @fluxor.versions[0].reify assert_nil @fluxor.versions[0].reify
assert_equal 'Some text.', @fluxor.versions[1].reify.name assert_equal 'Some text.', @fluxor.versions[1].reify.name
# Check values are stored as YAML. # Check values are stored as `YAML`.
assert_equal @original_fluxor_attributes, YAML.load(@fluxor.versions[1].object) assert_equal @original_fluxor_attributes, YAML.load(@fluxor.versions[1].object)
# This test can't consistently pass in Ruby1.8 because hashes do no preserve order, which means the order of the # This test can't consistently pass in Ruby1.8 because hashes do no preserve order, which means the order of the
# attributes in the YAML can't be ensured. # attributes in the `YAML` can't be ensured.
if RUBY_VERSION.to_f >= 1.9 if RUBY_VERSION.to_f >= 1.9
assert_equal YAML.dump(@original_fluxor_attributes), @fluxor.versions[1].object assert_equal YAML.dump(@original_fluxor_attributes), @fluxor.versions[1].object
end end
@ -33,7 +33,7 @@ class SerializerTest < ActiveSupport::TestCase
context 'JSON Serializer' do context 'JSON Serializer' do
setup do setup do
PaperTrail.configure do |config| PaperTrail.configure do |config|
config.serializer = PaperTrail::Serializers::Json config.serializer = PaperTrail::Serializers::JSON
end end
Fluxor.instance_eval <<-END Fluxor.instance_eval <<-END
@ -46,7 +46,7 @@ class SerializerTest < ActiveSupport::TestCase
end end
teardown do teardown do
PaperTrail.config.serializer = PaperTrail::Serializers::Yaml PaperTrail.config.serializer = PaperTrail::Serializers::YAML
end end
should 'reify with JSON serializer' do should 'reify with JSON serializer' do
@ -88,7 +88,7 @@ class SerializerTest < ActiveSupport::TestCase
end end
teardown do teardown do
PaperTrail.config.serializer = PaperTrail::Serializers::Yaml PaperTrail.config.serializer = PaperTrail::Serializers::YAML
end end
should 'reify with custom serializer' do should 'reify with custom serializer' do

View File

@ -1,6 +1,6 @@
require 'test_helper' require 'test_helper'
class JsonTest < ActiveSupport::TestCase class JSONTest < ActiveSupport::TestCase
setup do setup do
# Setup a hash with random values # Setup a hash with random values
@ -17,23 +17,23 @@ class JsonTest < ActiveSupport::TestCase
context '`load` class method' do context '`load` class method' do
should 'exist' do should 'exist' do
assert PaperTrail::Serializers::Json.respond_to?(:load) assert PaperTrail::Serializers::JSON.respond_to?(:load)
end end
should '`deserialize` JSON to Ruby' do should '`deserialize` JSON to Ruby' do
assert_equal @hash, PaperTrail::Serializers::Json.load(@hash_as_json) assert_equal @hash, PaperTrail::Serializers::JSON.load(@hash_as_json)
assert_equal @array, PaperTrail::Serializers::Json.load(@array_as_json) assert_equal @array, PaperTrail::Serializers::JSON.load(@array_as_json)
end end
end end
context '`dump` class method' do context '`dump` class method' do
should 'exist' do should 'exist' do
assert PaperTrail::Serializers::Json.respond_to?(:dump) assert PaperTrail::Serializers::JSON.respond_to?(:dump)
end end
should '`serialize` Ruby to JSON' do should '`serialize` Ruby to JSON' do
assert_equal @hash_as_json, PaperTrail::Serializers::Json.dump(@hash) assert_equal @hash_as_json, PaperTrail::Serializers::JSON.dump(@hash)
assert_equal @array_as_json, PaperTrail::Serializers::Json.dump(@array) assert_equal @array_as_json, PaperTrail::Serializers::JSON.dump(@array)
end end
end end

View File

@ -1,7 +1,7 @@
require 'test_helper' require 'test_helper'
module CustomYamlSerializer module CustomYamlSerializer
extend PaperTrail::Serializers::Yaml extend PaperTrail::Serializers::YAML
def self.load(string) def self.load(string)
parsed_value = super(string) parsed_value = super(string)

View File

@ -17,23 +17,23 @@ class YamlTest < ActiveSupport::TestCase
context '`load` class method' do context '`load` class method' do
should 'exist' do should 'exist' do
assert PaperTrail::Serializers::Yaml.respond_to?(:load) assert PaperTrail::Serializers::YAML.respond_to?(:load)
end end
should '`deserialize` YAML to Ruby' do should 'deserialize `YAML` to Ruby' do
assert_equal @hash, PaperTrail::Serializers::Yaml.load(@hash_as_yaml) assert_equal @hash, PaperTrail::Serializers::YAML.load(@hash_as_yaml)
assert_equal @array, PaperTrail::Serializers::Yaml.load(@array_as_yaml) assert_equal @array, PaperTrail::Serializers::YAML.load(@array_as_yaml)
end end
end end
context '`dump` class method' do context '`dump` class method' do
should 'exist' do should 'exist' do
assert PaperTrail::Serializers::Yaml.respond_to?(:dump) assert PaperTrail::Serializers::YAML.respond_to?(:dump)
end end
should '`serialize` Ruby to YAML' do should 'serialize Ruby to `YAML`' do
assert_equal @hash_as_yaml, PaperTrail::Serializers::Yaml.dump(@hash) assert_equal @hash_as_yaml, PaperTrail::Serializers::YAML.dump(@hash)
assert_equal @array_as_yaml, PaperTrail::Serializers::Yaml.dump(@array) assert_equal @array_as_yaml, PaperTrail::Serializers::YAML.dump(@array)
end end
end end