aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/hash/except.rb
diff options
context:
space:
mode:
Diffstat (limited to 'activesupport/lib/active_support/core_ext/hash/except.rb')
-rw-r--r--activesupport/lib/active_support/core_ext/hash/except.rb24
1 files changed, 24 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/hash/except.rb b/activesupport/lib/active_support/core_ext/hash/except.rb
new file mode 100644
index 0000000000..6258610c98
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/hash/except.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+class Hash
+ # Returns a hash that includes everything except given keys.
+ # hash = { a: true, b: false, c: nil }
+ # hash.except(:c) # => { a: true, b: false }
+ # hash.except(:a, :b) # => { c: nil }
+ # hash # => { a: true, b: false, c: nil }
+ #
+ # This is useful for limiting a set of parameters to everything but a few known toggles:
+ # @person.update(params[:person].except(:admin))
+ def except(*keys)
+ dup.except!(*keys)
+ end
+
+ # Removes the given keys from hash and returns it.
+ # hash = { a: true, b: false, c: nil }
+ # hash.except!(:c) # => { a: true, b: false }
+ # hash # => { a: true, b: false }
+ def except!(*keys)
+ keys.each { |key| delete(key) }
+ self
+ end
+end