From e768c519fb6015e00961702a5165c6dab548a954 Mon Sep 17 00:00:00 2001 From: Gaurish Sharma Date: Sun, 17 May 2015 16:21:34 +0530 Subject: Add bang version to OrderedOptions By: Aditya Sanghi(@asanghi) Gaurish Sharma(gaurish) --- activesupport/CHANGELOG.md | 15 +++++++++++++++ activesupport/lib/active_support/ordered_options.rb | 7 ++++++- activesupport/test/ordered_options_test.rb | 15 +++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) (limited to 'activesupport') 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 -- cgit v1.2.3