summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorBobby McDonald <bobbymcwho@gmail.com>2019-08-13 23:38:06 -0400
committerBobby McDonald <bobbymcwho@gmail.com>2019-08-14 12:31:10 -0400
commit3e64a4f58d24b4741209b0678dbf62c00fe6cd03 (patch)
tree33fb8d9e9dfae87274f8dff1f4d7a2fc18e31dc7 /lib
parent1de19bff87e1f75192af2788e8ee47cda593ade2 (diff)
downloadhashie-3e64a4f58d24b4741209b0678dbf62c00fe6cd03.tar.gz
Implement non-destructive hash methods
When calling the following non-destructive hash methods: :compact :invert :reject :select :slice :transform_keys :transform_values we would be returned an instance of a standard Hash rather than a Mash (or subclass). This changes that behavior to instead return an instance of the class the method was called on.
Diffstat (limited to 'lib')
-rw-r--r--lib/hashie/mash.rb42
1 files changed, 42 insertions, 0 deletions
diff --git a/lib/hashie/mash.rb b/lib/hashie/mash.rb
index 06cef59..bac93a4 100644
--- a/lib/hashie/mash.rb
+++ b/lib/hashie/mash.rb
@@ -207,6 +207,31 @@ module Hashie
super(*keys.map { |key| convert_key(key) })
end
+ # Returns a new instance of the class it was called on, with nil values
+ # removed.
+ def compact
+ self.class.new(super)
+ end
+
+ # Returns a new instance of the class it was called on, using its keys as
+ # values, and its values as keys. The new values and keys will always be
+ # strings.
+ def invert
+ self.class.new(super)
+ end
+
+ # Returns a new instance of the class it was called on, containing elements
+ # for which the given block returns false.
+ def reject(&blk)
+ self.class.new(super(&blk))
+ end
+
+ # Returns a new instance of the class it was called on, containing elements
+ # for which the given block returns true.
+ def select(&blk)
+ self.class.new(super(&blk))
+ end
+
alias regular_dup dup
# Duplicates the current mash as a new mash.
def dup
@@ -320,6 +345,23 @@ module Hashie
end
end
+ with_minimum_ruby('2.4.0') do
+ def transform_values(&blk)
+ self.class.new(super(&blk))
+ end
+ end
+
+ with_minimum_ruby('2.5.0') do
+ def slice(*keys)
+ string_keys = keys.map { |key| convert_key(key) }
+ self.class.new(super(*string_keys))
+ end
+
+ def transform_keys(&blk)
+ self.class.new(super(&blk))
+ end
+ end
+
protected
def method_name_and_suffix(method_name)