Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/screenplay/datatype-extensions.rb
Overview
Adds a few extra methods to the standard Hash
Instance Method Summary collapse
- #get_value_from_path(path, sep_char = '.') ⇒ Object
-
#remove_nil_values! ⇒ Object
Removes all nil values from the hash.
-
#stringify_keys!(recursive = true) ⇒ Object
Changes all keys to strings.
-
#symbolize_keys!(recursive = true) ⇒ Object
Changes all keys to symbols.
Instance Method Details
#get_value_from_path(path, sep_char = '.') ⇒ Object
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/screenplay/datatype-extensions.rb', line 56 def get_value_from_path(path, sep_char = '.') node, rest = path.to_s.split(sep_char, 2) index = node.gsub(/(^.*\[|\]$)/, '') value = nil if node == index value = self[node.to_sym] || self[node.to_s] elsif index.numeric? node.gsub!(/\[(\w+)\]$/, '') if self.include?(node.to_sym) && self[node.to_sym].is_a?(Array) value = self[node.to_sym][index.to_i] elsif self.include?(node.to_s) && self[node.to_s].is_a?(Array) value = self[node.to_s][index.to_i] else value = nil end end return nil if value.nil? return value if rest.nil? || rest.empty? return value.is_a?(Hash) ? value.get_value_from_path(rest, sep_char) : nil end |
#remove_nil_values! ⇒ Object
Removes all nil values from the hash. If the value is an array or hash, it will do this recursively.
26 27 28 29 |
# File 'lib/screenplay/datatype-extensions.rb', line 26 def remove_nil_values! self.delete_if { |_, v| v.nil? } self.each { |_, v| v.remove_nil_values! if (v.is_a?(Hash) || v.is_a?(Array)) } end |
#stringify_keys!(recursive = true) ⇒ Object
Changes all keys to strings. If the value is an array or hash, it will do this recursively.
45 46 47 48 49 50 51 52 53 54 |
# File 'lib/screenplay/datatype-extensions.rb', line 45 def stringify_keys!(recursive = true) self.keys.each do |key| if !key.is_a?(String) val = self.delete(key) val.stringify_keys! if (recursive && (val.is_a?(Hash) || val.is_a?(Array))) self[(key.to_s rescue key) || key] = val end end return self end |
#symbolize_keys!(recursive = true) ⇒ Object
Changes all keys to symbols. If the value is an array or hash, it will do this recursively.
32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/screenplay/datatype-extensions.rb', line 32 def symbolize_keys!(recursive = true) self.keys.each { | key | if !key.is_a?(Symbol) val = self.delete(key) val.symbolize_keys! if (recursive && (val.is_a?(Hash) || val.is_a?(Array))) self[(key.to_sym rescue key) || key] = val end self[key.to_sym].symbolize_keys! if (recursive && (self[key.to_sym].is_a?(Hash) || self[key.to_sym].is_a?(Array))) } return self end |