diff options
author | Gaurish Sharma <contact@gaurishsharma.com> | 2015-05-17 16:21:34 +0530 |
---|---|---|
committer | Gaurish Sharma <contact@gaurishsharma.com> | 2015-05-23 14:25:06 +0530 |
commit | e768c519fb6015e00961702a5165c6dab548a954 (patch) | |
tree | 00b4f408a6dd91c28f74efad7c64bc4f74bd0e07 | |
parent | 42e66fac38b54dd53d062fb5d3376218ed2ffdae (diff) | |
download | rails-e768c519fb6015e00961702a5165c6dab548a954.tar.gz rails-e768c519fb6015e00961702a5165c6dab548a954.tar.bz2 rails-e768c519fb6015e00961702a5165c6dab548a954.zip |
Add bang version to OrderedOptions
By:
Aditya Sanghi(@asanghi)
Gaurish Sharma(gaurish)
-rw-r--r-- | activesupport/CHANGELOG.md | 15 | ||||
-rw-r--r-- | activesupport/lib/active_support/ordered_options.rb | 7 | ||||
-rw-r--r-- | activesupport/test/ordered_options_test.rb | 15 |
3 files changed, 36 insertions, 1 deletions
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index d6fa651e39..fe8c283fc7 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -1,3 +1,18 @@ +* 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 hell as important secret password is not specified + end + + After: + + slack_url = Rails.application.secrets.slack_url! + + *Aditya Sanghi*, *Gaurish Sharma* + * Patch `Delegator` to work with `#try`. Fixes #5790. diff --git a/activesupport/lib/active_support/ordered_options.rb b/activesupport/lib/active_support/ordered_options.rb index a33e2c58a9..46c0da452d 100644 --- a/activesupport/lib/active_support/ordered_options.rb +++ b/activesupport/lib/active_support/ordered_options.rb @@ -31,7 +31,12 @@ module ActiveSupport 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 nil or undefined")) + else + self[name_string] + end end end diff --git a/activesupport/test/ordered_options_test.rb b/activesupport/test/ordered_options_test.rb index fdc745b23b..bffefb6ad9 100644 --- a/activesupport/test/ordered_options_test.rb +++ b/activesupport/test/ordered_options_test.rb @@ -85,4 +85,19 @@ class OrderedOptionsTest < ActiveSupport::TestCase 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 |