Skip to content

Commit

Permalink
Deprecate writing directly to attributes hash.
Browse files Browse the repository at this point in the history
  • Loading branch information
tpendragon committed Dec 1, 2018
1 parent aed1e29 commit 38b5fea
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
28 changes: 27 additions & 1 deletion lib/valkyrie/resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,35 @@ def optimistic_locking_enabled?
self.class.optimistic_locking_enabled?
end

class DeprecatedHashWrite < Hash
def []=(_k, _v)
warn "[DEPRECATION] Writing directly to attributes has been deprecated." \
" Please use #set_value(k, v) instead." \
" In the next major version, this hash will be frozen. \n" \
"Called from #{Gem.location_of_caller.join(':')}"
super
end

def delete(*_args)
warn "[DEPRECATION] Writing directly to attributes has been deprecated." \
" Please use #set_value(k, v) instead." \
" In the next major version, this hash will be frozen. \n" \
"Called from #{Gem.location_of_caller.join(':')}"
super
end

def delete_if(*_args)
warn "[DEPRECATION] Writing directly to attributes has been deprecated." \
" Please use #set_value(k, v) instead." \
" In the next major version, this hash will be frozen. \n" \
"Called from #{Gem.location_of_caller.join(':')}"
super
end
end

# @return [Hash] Hash of attributes
def attributes
to_h.freeze
DeprecatedHashWrite.new.merge(to_h)
end

# @param name [Symbol] Attribute name
Expand Down
4 changes: 3 additions & 1 deletion lib/valkyrie/specs/shared_specs/resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,9 @@ class MyCustomResource < Valkyrie::Resource

expect(resource.attributes).to have_key(:bla)
expect(resource.attributes[:internal_resource]).to eq resource_klass.to_s
expect { resource.attributes[:internal_resource] = "bla" }.to raise_error "can't modify frozen Hash"
expect { resource.attributes[:internal_resource] = "bla" }.to output(/\[DEPRECATION\]/).to_stderr
expect { resource.attributes.delete_if { true } }.to output(/\[DEPRECATION\]/).to_stderr
expect { resource.attributes.delete(:internal_resource) }.to output(/\[DEPRECATION\]/).to_stderr

resource_klass.schema.delete(:bla)
end
Expand Down

0 comments on commit 38b5fea

Please sign in to comment.