Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/patches/core_ext/hash/flatten_keys.rb

Instance Method Summary collapse

Instance Method Details

#flatten_keys_to_arrayObject Also known as: flatten_keys

Returns a flat hash where all nested keys are collapsed into an array of keys.

hash = { person: { name: { first: 'Rob' }, age: '28' } }
hash.flatten_keys_to_array
=> {[:person, :name, :first] => "Rob", [:person, :age]=>"28" }


11
12
13
# File 'lib/patches/core_ext/hash/flatten_keys.rb', line 11

def flatten_keys_to_array
  _flatten_keys(self)
end

#flatten_keys_to_dotpathObject

Returns a flat hash where all nested keys are collapsed into a dot-separated string of keys.

hash = { person: { name: { first: 'Rob' }, age: '28' } }
hash.flatten_keys_to_dotpath
=> { 'person.name.first' => "Rob", 'person.age'=>"28" }


21
22
23
# File 'lib/patches/core_ext/hash/flatten_keys.rb', line 21

def flatten_keys_to_dotpath
  _flatten_keys(self, ->(*keys) { keys.join('.') })
end

#flatten_keys_to_html_attributeObject

Returns a flat hash where all nested keys are collapsed into a dast-separated string of keys.

hash = { person: { name: { first: 'Rob' }, age: '28' } }
hash.flatten_keys_to_html_attribute
=> { 'person-name-first' => "Rob", 'person-age'=>"28" }


30
31
32
# File 'lib/patches/core_ext/hash/flatten_keys.rb', line 30

def flatten_keys_to_html_attribute
  _flatten_keys(self, ->(*keys) { keys.join('-') })
end

#flatten_keys_to_rails_paramObject

Returns a flat hash where all nested keys are collapsed into a string of keys fitting the Rails request param pattern.

hash = { person: { name: { first: 'Rob' }, age: '28' } }
hash.flatten_keys_to_rails_param
=> { 'person[name][first]' => "Rob", 'person[age]'=>"28" }


40
41
42
# File 'lib/patches/core_ext/hash/flatten_keys.rb', line 40

def flatten_keys_to_rails_param
  _flatten_keys(self, ->(*keys) { keys.map(&:to_s).reduce { |memo, key| memo + "[#{key}]" } })
end