Skip to content

Commit

Permalink
Ensure we return nils for unset keys in Dash
Browse files Browse the repository at this point in the history
In 0bd18ee, we stopped setting any `nil` values on the Dash in order to
prevent co-dependent properties from throwing errors. This is a problem
because it means that when you explicitly set `nil` as a value for
a property, it's not set on the underlying hash and you will not get it
back if you call `#to_h`.

By explicitly setting a nil value on the result of `#to_h` for unset
keys, we can avoid this issue and return what the called expects.
  • Loading branch information
michaelherold committed Nov 17, 2019
1 parent d25a995 commit d6718cc
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/hashie/dash.rb
Expand Up @@ -183,6 +183,15 @@ def update_attributes!(attributes)
assert_required_attributes_set!
end

def to_h
result = super
self.class.properties.each do |property|
result[property] ||= nil
end
yield result if block_given?
result
end

private

def initialize_attributes(attributes)
Expand Down
9 changes: 9 additions & 0 deletions spec/hashie/dash_spec.rb
Expand Up @@ -446,6 +446,15 @@ class KeepingMash < Hashie::Mash
)
end
end

describe '#to_hash' do
it 'does not write out keys with nil values' do
expect(DashTest.new(first_name: 'Bob', email: nil).to_hash).to eq(
first_name: 'Bob',
count: 0
)
end
end
end

describe Hashie::Dash, 'inheritance' do
Expand Down

0 comments on commit d6718cc

Please sign in to comment.