Class: Hash

Inherits:
Object show all
Defined in:
lib/core_ext/hash.rb,
lib/core_ext/blank.rb

Overview

reopening Hash class

Instance Method Summary collapse

Instance Method Details

#reverse_merge(other_hash) ⇒ Hash

Performs a non-destructive reverse merge with another hash This is particularly useful for initializing an options hash with default values.

is equivalent to

options = { size: 25, velocity: 10 }.merge(options)

Examples:

A basic example


options = options.reverse_merge(size: 25, velocity: 10)

Parameters:

  • other_hash (Hash)

    The hash to merge into

Returns:

  • (Hash)

    A new hash with other_hash merged into self



45
46
47
# File 'lib/core_ext/hash.rb', line 45

def reverse_merge(other_hash)
  other_hash.merge(self)
end

#reverse_merge!(other_hash) ⇒ Hash Also known as: reverse_update

Performs a destructive reverse merge with another hash. Modifies the original hash by merging in the provided hash while keeping existing values.

Examples:

options = { size: 10 }
options.reverse_merge!(size: 25, velocity: 10)
# => { size: 10, velocity: 10 }

Parameters:

  • other_hash (Hash)

    The hash to merge into self

Returns:

  • (Hash)

    The modified hash with other_hash merged in



63
64
65
66
# File 'lib/core_ext/hash.rb', line 63

def reverse_merge!(other_hash)
  # right wins if there is no left
  merge!(other_hash) { |_key, left, _right| left }
end

#to_html_attributes(empties = nil) ⇒ String

Converts a hash into HTML attribute string representation.

Examples:

{class: 'button', id: 'submit'}.to_html_attributes #=> 'class="button" id="submit"'
{name: nil, id: 'test'}.to_html_attributes(true) #=> 'id="test"'

Parameters:

  • empties (Boolean, nil) (defaults to: nil)

    If provided and not nil, will exclude keys with blank values

Returns:

  • (String)

    HTML attribute string with keys sorted alphabetically



18
19
20
21
22
23
24
25
26
27
# File 'lib/core_ext/hash.rb', line 18

def to_html_attributes(empties = nil)
  hash = dup
  hash.reject! { |_k, v| v.blank? } unless empties.nil?
  out = ''
  hash.keys.sort.each do |key| # NB!! sorting output order of attributes alphabetically
    val = hash[key].is_a?(Array) ? hash[key].join('_') : hash[key].to_s
    out << "#{key}=\"#{val}\" "
  end
  out.strip
end