diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index 36be5fe93665583ad4aa79e4972ee452cefc2aef..2fac308d2ecb3ba6f95790a04a1a0fd746d6a0a3 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -1,3 +1,20 @@ +* 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. diff --git a/activesupport/lib/active_support/ordered_options.rb b/activesupport/lib/active_support/ordered_options.rb index a33e2c58a9a3e0c9513969432b7e0295f9040cfd..ebf2a9bc29f12b49fb5a846c25a2e43a092f9ecc 100644 --- a/activesupport/lib/active_support/ordered_options.rb +++ b/activesupport/lib/active_support/ordered_options.rb @@ -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 diff --git a/activesupport/test/ordered_options_test.rb b/activesupport/test/ordered_options_test.rb index fdc745b23bc1d622757bc4c2fde169d628ce3f1c..18767a353604f07c318f7d5588360a631d183421 100644 --- a/activesupport/test/ordered_options_test.rb +++ b/activesupport/test/ordered_options_test.rb @@ -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