Skip to content
This repository has been archived by the owner on Jun 30, 2018. It is now read-only.

Commit

Permalink
[PERSISTENCE][FIX] Changing instance properties should not affect pro…
Browse files Browse the repository at this point in the history
…perty default

Hash and Array... were passed to property as reference, not object
  • Loading branch information
vhyza committed Mar 1, 2012
1 parent 04ff4a8 commit 4bb4cb0
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/tire/model/persistence/attributes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def property(name, options = {})

# Define attribute reader:
define_method("#{name}") do
instance_variable_get(:"@#{name}") || self.class.property_defaults[name.to_sym]
instance_variable_get(:"@#{name}")
end

# Define attribute writer:
Expand Down Expand Up @@ -82,7 +82,14 @@ module InstanceMethods
attr_accessor :id

def initialize(attributes={})
__update_attributes(attributes)
# Make a copy of objects in the property defaults hash, so default values such as `[]` or `{ foo: [] }` are left intact
property_defaults = self.class.property_defaults.inject({}) do |hash, item|
key, value = item
hash[key.to_s] = value.class.respond_to?(:new) ? value.clone : value
hash
end

__update_attributes(property_defaults.merge(attributes))
end

def attributes
Expand Down
1 change: 1 addition & 0 deletions test/models/persistent_article_with_defaults.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ class PersistentArticleWithDefaults
property :published_on
property :tags, :default => []
property :hidden, :default => false
property :options, :default => {:switches => []}

end
10 changes: 10 additions & 0 deletions test/unit/model_persistence_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,16 @@ class << a
assert_equal false, article.hidden
end

should "not affect default value" do
article = PersistentArticleWithDefaults.new :title => 'Test'
article.tags << "ruby"

article.options[:switches] << "switch_1"

assert_equal [], PersistentArticleWithDefaults.new.tags
assert_equal [], PersistentArticleWithDefaults.new.options[:switches]
end

should "have query method for attribute" do
assert_equal true, @article.title?
end
Expand Down

0 comments on commit 4bb4cb0

Please sign in to comment.