Skip to content

Commit

Permalink
Fix assign attributes so it behaves like original
Browse files Browse the repository at this point in the history
  • Loading branch information
shioyama committed Oct 6, 2016
1 parent b44a06d commit e36913a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 16 deletions.
16 changes: 8 additions & 8 deletions lib/globalize/active_record/instance_methods.rb
Expand Up @@ -12,14 +12,15 @@ def attributes
end

def attributes=(new_attributes, *options)
return unless new_attributes.is_a?(Hash)
assign_attributes(new_attributes, *options)
super unless new_attributes.respond_to?(:stringify_keys) && new_attributes.present?
attributes = new_attributes.stringify_keys
with_given_locale(attributes) { super(attributes.except("locale"), *options) }
end

def assign_attributes(new_attributes, *options)
return unless new_attributes
attributes = new_attributes.symbolize_keys
with_given_locale(attributes) { super(attributes.except(:locale), *options) }
super unless new_attributes.respond_to?(:stringify_keys) && new_attributes.present?
attributes = new_attributes.stringify_keys
with_given_locale(attributes) { super(attributes.except("locale"), *options) }
end

def write_attribute(name, value, options = {})
Expand Down Expand Up @@ -200,9 +201,9 @@ def save_translations!
end

def with_given_locale(_attributes, &block)
attributes = _attributes.symbolize_keys
attributes = _attributes.stringify_keys

if locale = attributes.try(:delete, :locale)
if locale = attributes.try(:delete, "locale")
Globalize.with_locale(locale, &block)
else
yield
Expand All @@ -216,7 +217,6 @@ def without_fallbacks
ensure
self.fallbacks_for_empty_translations = before
end

end
end
end
14 changes: 6 additions & 8 deletions test/globalize/attributes_test.rb
Expand Up @@ -164,12 +164,10 @@ class AttributesTest < MiniTest::Spec
assert_equal post.title, 'newtitle'
end

it 'does nothing if attributes is not a hash' do
it 'raises ArgumentError if attributes is blank' do
post = Post.create(:title => 'title')
post.attributes = nil
assert_equal 'title', post.title
post.attributes = []
assert_equal 'title', post.title
assert_raises(ArgumentError) { post.attributes = nil }
assert_raises(ArgumentError) { post.attributes = [] }
end

it 'does not modify arguments passed in' do
Expand All @@ -193,10 +191,10 @@ class AttributesTest < MiniTest::Spec
assert_equal post.title, 'newtitle'
end

it 'does nothing if attributes is nil' do
it 'raises ArgumentError if attributes is blank' do
post = Post.create(:title => 'title')
post.assign_attributes(nil)
assert_equal 'title', post.title
assert_raises(ArgumentError) { post.assign_attributes(nil) }
assert_raises(ArgumentError) { post.assign_attributes([]) }
end

it 'does not modify arguments passed in' do
Expand Down

0 comments on commit e36913a

Please sign in to comment.