Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Ensure that rich objects can be serialized for MongoMapper audits on …

…updation
  • Loading branch information...
commit 5388ff706d6e4a5771aaf77630b10995fd590a27 1 parent ec4732f
Steve Richert laserlemon authored
1  lib/audited/adapters/mongo_mapper.rb
View
@@ -1,5 +1,6 @@
require 'mongo_mapper'
require 'audited/auditor'
+require 'audited/adapters/mongo_mapper/audited_changes'
require 'audited/adapters/mongo_mapper/audit'
module Audited::Auditor::ClassMethods
2  lib/audited/adapters/mongo_mapper/audit.rb
View
@@ -25,7 +25,7 @@ class Audit
key :user_type, String
key :username, String
key :action, String
- key :audited_changes, Hash
+ key :audited_changes, AuditedChanges
key :version, Integer, :default => 0
key :comment, String
key :remote_address, String
26 lib/audited/adapters/mongo_mapper/audited_changes.rb
View
@@ -0,0 +1,26 @@
+module Audited
+ module Adapters
+ module MongoMapper
+ class AuditedChanges < ::Hash
+ def self.from_mongo(changes)
+ changes.is_a?(Hash) ? new.replace(changes) : changes
+ end
+
+ def self.to_mongo(changes)
+ if changes.is_a?(Hash)
+ changes.inject({}) do |memo, (key, value)|
+ memo[key] = if value.is_a?(Array)
+ value.map{|v| v.class.to_mongo(v) }
+ else
+ value
+ end
+ memo
+ end
+ else
+ changes
+ end
+ end
+ end
+ end
+ end
+end
13 spec/audited/adapters/mongo_mapper/auditor_spec.rb
View
@@ -138,6 +138,19 @@ class Secret
expect { @user.update_attribute :activated, '1' }.to_not change( Audited.audit_class, :count )
end
+ it "saves audits of rich objects" do
+ user = Models::MongoMapper::RichObjectUser.create!(:name => 'Bart Simpson')
+
+ expect {
+ user.update_attribute(:name, 'O.J. Simpson')
+ }.to_not raise_error(BSON::InvalidDocument)
+
+ change = user.audits.all.last.audited_changes['name']
+ change.should be_all{|c| c.is_a?(String) }
+ change[0].should == 'Bart Simpson'
+ change[1].should == 'O.J. Simpson'
+ end
+
describe "with no dirty changes" do
it "does not create an audit if the record is not changed" do
expect {
36 spec/support/mongo_mapper/models.rb
View
@@ -170,5 +170,41 @@ class OnCreateUpdate
audited :on => [:create, :update]
end
+
+ class RichObjectUser
+ include ::MongoMapper::Document
+
+ class Name
+ attr_accessor :first_name, :last_name
+
+ def self.from_mongo(value)
+ case value
+ when String then new(*value.split)
+ when self then value
+ end
+ end
+
+ def self.to_mongo(value)
+ case value
+ when String then value
+ when self then value.to_s
+ end
+ end
+
+ def initialize(first_name, last_name)
+ self.first_name, self.last_name = first_name, last_name
+ end
+
+ def to_s
+ [first_name, last_name].compact.join(' ')
+ end
+ end
+
+ key :name, Name
+
+ attr_accessible :name
+
+ audited
+ end
end
end
Please sign in to comment.
Something went wrong with that request. Please try again.