Skip to content

Commit

Permalink
check for changed attributes accurately with string values [Aron Atkins]
Browse files Browse the repository at this point in the history
git-svn-id: http://svn.techno-weenie.net/projects/plugins/acts_as_versioned@2472 567b1171-46fb-0310-a4c9-b4bef9110e78
  • Loading branch information
technoweenie committed Nov 15, 2006
1 parent 51b7540 commit 964ab7f
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
8 changes: 5 additions & 3 deletions lib/acts_as_versioned.rb
Expand Up @@ -392,10 +392,12 @@ def next_version
def clear_changed_attributes
self.changed_attributes = []
end

def write_changed_attribute(attr_name, attr_value)
(self.changed_attributes ||= []) << attr_name.to_s unless self.changed?(attr_name) or self.send(attr_name) == attr_value
write_attribute(attr_name.to_s, attr_value)
# Convert to db type for comparison. Avoids failing Float<=>String comparisons.
attr_value_for_db = self.class.columns_hash[attr_name.to_s].type_cast(attr_value)
(self.changed_attributes ||= []) << attr_name.to_s unless self.changed?(attr_name) || self.send(attr_name) == attr_value_for_db
write_attribute(attr_name, attr_value_for_db)
end

private
Expand Down
17 changes: 16 additions & 1 deletion test/schema.rb
Expand Up @@ -50,4 +50,19 @@
t.column :version, :integer
t.column :updated_at, :datetime
end
end

create_table :landmarks, :force => true do |t|
t.column :name, :string
t.column :latitude, :float
t.column :longitude, :float
t.column :version, :integer
end

create_table :landmark_versions, :force => true do |t|
t.column :landmark_id, :integer
t.column :name, :string
t.column :latitude, :float
t.column :longitude, :float
t.column :version, :integer
end
end
12 changes: 11 additions & 1 deletion test/versioned_test.rb
Expand Up @@ -3,7 +3,7 @@
require File.join(File.dirname(__FILE__), 'fixtures/widget')

class VersionedTest < Test::Unit::TestCase
fixtures :pages, :page_versions, :locked_pages, :locked_pages_revisions, :authors
fixtures :pages, :page_versions, :locked_pages, :locked_pages_revisions, :authors, :landmarks, :landmark_versions

def test_saves_versioned_copy
p = Page.create :title => 'first title', :body => 'first body'
Expand Down Expand Up @@ -300,4 +300,14 @@ def test_versioned_records_should_belong_to_parent
page_version = page.versions.last
assert_equal page, page_version.page
end

def test_unchanged_attributes
landmarks(:washington).attributes = landmarks(:washington).attributes
assert !landmarks(:washington).changed?
end

def test_unchanged_string_attributes
landmarks(:washington).attributes = landmarks(:washington).attributes.inject({}) { |params, (key, value)| params.update key => value.to_s }
assert !landmarks(:washington).changed?
end
end

0 comments on commit 964ab7f

Please sign in to comment.