diff options
author | Michael Herold <opensource@michaeljherold.com> | 2020-10-23 21:57:10 -0500 |
---|---|---|
committer | Michael Herold <> | 2020-10-23 21:57:10 -0500 |
commit | f152e25912d0b93ff08b8964eb757200ad4b6f32 (patch) | |
tree | d357a27b5b2b8408d87f6d400cb5fe8d52259d8c /lib | |
parent | 14e923d899183595abb5ee096c29e1de707fcc04 (diff) | |
download | hashie-f152e25912d0b93ff08b8964eb757200ad4b6f32.tar.gz |
Fix inconsistencies with Dash defaults
The normal behavior of Dash with respect to property defaults differed
from the behavior of a Dash/Trash with IgnoreUndeclared mixed in. This
is because some situations called the defaults and some did not.
This change normalizes the behavior so that all situations where the
defaults should be used to override unset values behave consistently,
as well as all situations where the default should not override a `nil`
value.
Diffstat (limited to 'lib')
-rw-r--r-- | lib/hashie/dash.rb | 25 | ||||
-rw-r--r-- | lib/hashie/extensions/ignore_undeclared.rb | 9 |
2 files changed, 13 insertions, 21 deletions
diff --git a/lib/hashie/dash.rb b/lib/hashie/dash.rb index 460790b..785d94d 100644 --- a/lib/hashie/dash.rb +++ b/lib/hashie/dash.rb @@ -104,19 +104,6 @@ module Hashie def initialize(attributes = {}, &block) super(&block) - self.class.defaults.each_pair do |prop, value| - self[prop] = begin - val = value.dup - if val.is_a?(Proc) - val.arity == 1 ? val.call(self) : val.call - else - val - end - rescue TypeError - value - end - end - initialize_attributes(attributes) assert_required_attributes_set! end @@ -173,13 +160,19 @@ module Hashie update_attributes(attributes) self.class.defaults.each_pair do |prop, value| - next unless self[prop].nil? + next unless fetch(prop, nil).nil? self[prop] = begin - value.dup + val = value.dup + if val.is_a?(Proc) + val.arity == 1 ? val.call(self) : val.call + else + val + end rescue TypeError value end end + assert_required_attributes_set! end @@ -189,7 +182,7 @@ module Hashie return unless attributes cleaned_attributes = attributes.reject { |_attr, value| value.nil? } - update_attributes(cleaned_attributes) + update_attributes!(cleaned_attributes) end def update_attributes(attributes) diff --git a/lib/hashie/extensions/ignore_undeclared.rb b/lib/hashie/extensions/ignore_undeclared.rb index 9b506dd..64cf0b6 100644 --- a/lib/hashie/extensions/ignore_undeclared.rb +++ b/lib/hashie/extensions/ignore_undeclared.rb @@ -31,12 +31,11 @@ module Hashie module IgnoreUndeclared def initialize_attributes(attributes) return unless attributes + klass = self.class - translations = klass.respond_to?(:translations) && klass.translations - attributes.each_pair do |att, value| - next unless klass.property?(att) || (translations && translations.include?(att)) - self[att] = value - end + translations = klass.respond_to?(:translations) && klass.translations || [] + + super(attributes.select { |attr, _| klass.property?(attr) || translations.include?(attr) }) end def property_exists?(property) |