From 98df995e2f0433d3d1abe46efd732bc8e20e31cc Mon Sep 17 00:00:00 2001 From: Michael Herold Date: Thu, 22 Oct 2020 21:07:14 -0500 Subject: Ensure all properties are set on exported Dash When exporting a Dash via `#to_h` or `#to_hash`, we expect all properties to be exported whether or not they are set. However, in the change that allows codependent properties to be nilified, we regressed the behavior of exporting all properties. There is a gotcha here, which I note in the tests for the specs. For posterity, MRI does not send the `#to_hash` method to anything that subclasses `Hash` when you double-splat it. Thus, we cannot override the behavior within MRI. For more information, see [this comment][1] where I detail the behavior of double-splat within MRI. Currently, JRuby also follows this behavior, but it's not guaranteed that other Rubies will. [1]: https://github.com/hashie/hashie/issues/353#issuecomment-363294886 --- lib/hashie/dash.rb | 7 +++++++ lib/hashie/extensions/dash/indifferent_access.rb | 9 +++++++++ 2 files changed, 16 insertions(+) (limited to 'lib') diff --git a/lib/hashie/dash.rb b/lib/hashie/dash.rb index 785d94d..cfb151e 100644 --- a/lib/hashie/dash.rb +++ b/lib/hashie/dash.rb @@ -156,6 +156,13 @@ module Hashie self end + def to_h + defaults = ::Hash[self.class.properties.map { |prop| [prop, self.class.defaults[prop]] }] + + defaults.merge(self) + end + alias to_hash to_h + def update_attributes!(attributes) update_attributes(attributes) diff --git a/lib/hashie/extensions/dash/indifferent_access.rb b/lib/hashie/extensions/dash/indifferent_access.rb index 204cae6..50d4f93 100644 --- a/lib/hashie/extensions/dash/indifferent_access.rb +++ b/lib/hashie/extensions/dash/indifferent_access.rb @@ -19,6 +19,15 @@ module Hashie end private_class_method :requires_class_methods? + def to_h + defaults = ::Hash[self.class.properties.map do |prop| + [Hashie::Extensions::IndifferentAccess.convert_key(prop), self.class.defaults[prop]] + end] + + defaults.merge(self) + end + alias to_hash to_h + module ClassMethods # Check to see if the specified property has already been # defined. -- cgit v1.2.1