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 5 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
9 changes: 8 additions & 1 deletion lib/ostruct.rb
Expand Up @@ -285,7 +285,9 @@ def dig(name, *names)

#
# Removes the named field from the object. Returns the value that the field
# contained if it was defined.
# contained if it was defined, else a NameError is raised.
jfrazx marked this conversation as resolved.
Show resolved Hide resolved
# Optionally, provide a value that will be returned in the event the
# deleting field does not exist.
#
# require "ostruct"
#
Expand All @@ -299,13 +301,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(s.to_sym, o.delete_field(s) { :foo })
jfrazx marked this conversation as resolved.
Show resolved Hide resolved

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