Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fallback value to OpenStruct delete_field #1409

Merged
merged 7 commits into from Jun 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 9 additions & 2 deletions lib/ostruct.rb
Expand Up @@ -326,8 +326,10 @@ def dig(name, *names)
end

#
# Removes the named field from the object. Returns the value that the field
# contained if it was defined.
# Removes the named field from the object and returns the value the field
# contained if it was defined. You may optionally provide a block.
# If the field is not defined, the result of the block is returned,
# or a NameError is raised if no block was given.
#
# require "ostruct"
#
Expand All @@ -341,13 +343,18 @@ def dig(name, *names)
# person.pension = nil
# person # => #<OpenStruct name="John", pension=nil>
#
# person.delete_field('number') # => NameError
#
# person.delete_field('number') { 8675_309 } # => 8675309
#
def delete_field(name)
sym = name.to_sym
begin
singleton_class.remove_method(sym, "#{sym}=")
rescue NameError
end
@table.delete(sym) do
return yield if block_given?
raise! NameError.new("no field `#{sym}' in #{self}", sym)
end
end
Expand Down
12 changes: 11 additions & 1 deletion test/ostruct/test_ostruct.rb
Expand Up @@ -89,7 +89,7 @@ def test_delete_field
a = o.delete_field :a
assert_not_respond_to(o, :a, bug)
assert_not_respond_to(o, :a=, bug)
assert_equal(a, 'a')
assert_equal('a', a)
s = Object.new
def s.to_sym
:foo
Expand All @@ -100,6 +100,16 @@ def s.to_sym
o.delete_field s
assert_not_respond_to(o, :foo)
assert_not_respond_to(o, :foo=)

assert_raise(NameError) { o.delete_field(s) }
assert_equal(:bar, o.delete_field(s) { :bar })

o[s] = :foobar
assert_respond_to(o, :foo)
assert_respond_to(o, :foo=)
assert_equal(:foobar, o.delete_field(s) { :baz })

assert_equal(42, OpenStruct.new(foo: 42).delete_field(:foo) { :bug })
end

def test_setter
Expand Down