提交 b1f6be9b 编写于 作者: R Rafael Mendonça França

Merge pull request #20208 from gaurish/raise_on_missing_ordered_options

Add bang version to OrderedOptions
* Add a bang version to `ActiveSupport::OrderedOptions` get methods which will raise
an `KeyError` if the value is `.blank?`
Before:
if (slack_url = Rails.application.secrets.slack_url).present?)
# Do something worthwhile
else
# Raise as important secret password is not specified
end
After:
slack_url = Rails.application.secrets.slack_url!
*Aditya Sanghi*, *Gaurish Sharma*
* Remove deprecated `Class#superclass_delegating_accessor`.
Use `Class#class_attribute` instead.
......
......@@ -31,7 +31,13 @@ def method_missing(name, *args)
if name_string.chomp!('=')
self[name_string] = args.first
else
self[name]
bangs = name_string.chomp!('!')
if bangs
fetch(name_string.to_sym).presence || raise(KeyError.new("#{name_string} is blank."))
else
self[name_string]
end
end
end
......
......@@ -85,4 +85,19 @@ def test_introspection
assert_equal 42, a.method(:blah=).call(42)
assert_equal 42, a.method(:blah).call
end
def test_raises_with_bang
a = ActiveSupport::OrderedOptions.new
a[:foo] = :bar
assert a.respond_to?(:foo!)
assert_nothing_raised { a.foo! }
assert_equal a.foo, a.foo!
assert_raises(KeyError) do
a.foo = nil
a.foo!
end
assert_raises(KeyError) { a.non_existing_key! }
end
end
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册