Module: Sparsify::UtilityMethods

Included in:
Sparsify
Defined in:
lib/sparsify/utility_methods.rb

Overview

The Utility Methods provide a significant (~4x) performance increase over extend-ing instance methods everywhere we need them.

Instance Method Summary collapse

Instance Method Details

#expand(sparse_hsh, sparse_key, options = {}, &block) ⇒ Object

Given a sparse hash, unsparsify a subset by address, returning a *modified copy* of the original sparse hash.

~~~ ruby sparse = => 2, ‘a.c.d’ => 4, ‘a.c.e’ => 3, ‘b.f’ => 4 Sparsify::expand(sparse, ‘a.c’) # => => 2, ‘a.c’ => {‘d’ => 4, ‘e’ => 3, ‘b.f’ => 4} ~~~

Parameters:

  • sparse_hsh (Hash{String=>Object})
  • sparse_key (String)

Returns:

  • (Object)


146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/sparsify/utility_methods.rb', line 146

def expand(sparse_hsh, sparse_key, *args)
  # if sparse_hsh includes our key, its value is already expanded.
  return sparse_hsh if sparse_hsh.include?(sparse_key)

  options = (args.last.kind_of?(Hash) ? args.pop : {})
  separator = options.fetch(:separator, DEFAULT_SEPARATOR)
  pattern = /\A#{Regexp.escape(sparse_key)}#{Regexp.escape(separator)}/i

  match = {}
  unmatch = {}
  sparse_hsh.each do |k, v|
    if pattern =~ k
      sk = k.gsub(pattern, '')
      match[sk] = v
    else
      unmatch[k] = v
    end
  end

  unmatch.update(sparse_key => unsparse(match, options)) unless match.empty?
  unmatch
end

#expand!(sparse_hsh, *args) ⇒ Object

Given a sparse hash, unsparsify a subset by address *in place* (@see Sparsify::UtilityMethods#expand)



171
172
173
# File 'lib/sparsify/utility_methods.rb', line 171

def expand!(sparse_hsh, *args)
  sparse_hsh.replace expand(sparse_hsh, *args)
end

#sparse(hsh, options = {}) ⇒ Hash<String,Object>

Returns a sparse version of the given hash

Parameters:

  • hsh (Hash<#to_s,Object>)

Returns:

  • (Hash<String,Object>)


47
48
49
50
51
52
# File 'lib/sparsify/utility_methods.rb', line 47

def sparse(hsh, options = {})
  enum = sparse_each(hsh, options)
  enum.each_with_object(Hash.new) do |(key, value), memo|
    memo[key] = value
  end
end

#sparse_each(hsh, options = {}) {|| ... } ⇒ void #sparse_each(hsh, options = {}) ⇒ Enumerator<(sparse_key,value)>

Provides a way to iterate through a deeply-nested hash as if it were a sparse-hash. Used internally for generating and deconstructing sparse hashes.

Overloads:

  • #sparse_each(hsh, options = {}) {|| ... } ⇒ void

    This method returns an undefined value.

    Yields once per key in sparse version of itself.

    Parameters:

    • hsh (Hash<#to_s,Object>)

    Yield Parameters:

    • ((sparse_key,value))
  • #sparse_each(hsh, options = {}) ⇒ Enumerator<(sparse_key,value)>

    Parameters:

    • hsh (Hash<#to_s,Object>)

    Returns:

    • (Enumerator<(sparse_key,value)>)


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/sparsify/utility_methods.rb', line 22

def sparse_each(hsh, options = {}, &block)
  return enum_for(:sparse_each, hsh, options) unless block_given?

  inherited_prefix = options.fetch(:prefix, nil)
  separator = options.fetch(:separator, DEFAULT_SEPARATOR)
  sparse_array = options.fetch(:sparse_array, false)

  hsh.each do |partial_key, value|
    key = escaped_join(inherited_prefix, partial_key.to_s, separator)
    if value.kind_of?(Hash) && !value.empty?
      sparse_each(value, options.merge(prefix: key), &block)
    elsif sparse_array && value.kind_of?(Array) && !value.empty?
      zps = (sparse_array == :zero_pad ? "%0#{value.count.to_s.size}d" : '%d')# zero-pad string
      sparse_each(value.count.times.map(&zps.method(:%)).zip(value), options.merge(prefix: key), &block)
    else
      yield key, value
    end
  end
end

#sparse_fetch(hsh, sparse_key, default, options = {}) ⇒ Object #sparse_fetch(hsh, sparse_key, options = {}, &block) ⇒ Object #sparse_fetch(hsh, sparse_key, options = {}) ⇒ Object

Fetch a sparse key from the given deeply-nested hash.

Overloads:

  • #sparse_fetch(hsh, sparse_key, default, options = {}) ⇒ Object

    Parameters:

    • hsh (Hash<#to_s,Object>)
    • sparse_key (#to_s)
    • default (Object)

      returned if sparse key not found

    Returns:

    • (Object)
  • #sparse_fetch(hsh, sparse_key, options = {}, &block) ⇒ Object

    Parameters:

    • hsh (Hash<#to_s,Object>)
    • sparse_key (#to_s)

    Yield Returns:

    • is returned if key not found

    Returns:

    • (Object)
  • #sparse_fetch(hsh, sparse_key, options = {}) ⇒ Object

    Parameters:

    • hsh (Hash<#to_s,Object>)
    • sparse_key (#to_s)

    Returns:

    • (Object)

    Raises:

    • KeyError if key not found



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/sparsify/utility_methods.rb', line 98

def sparse_fetch(hsh, sparse_key, *args, &block)
  options = ( args.last.kind_of?(Hash) ? args.pop : {})
  default = args.pop

  separator = options.fetch(:separator, DEFAULT_SEPARATOR)

  escaped_split(sparse_key, separator).reduce(hsh) do |memo, kp|
    if memo.kind_of?(Hash) and memo.has_key?(kp)
      memo.fetch(kp)
    elsif default
      return default
    elsif block_given?
      return yield
    else
      raise KeyError, sparse_key
    end
  end
end

#sparse_get(hsh, sparse_key, options = {}) ⇒ Object

Get a sparse key from the given deeply-nested hash, or return nil if key not found.

Worth noting is that Hash#default_proc is not used, as the intricacies of implementation would lead to all sorts of terrible surprises.

Parameters:

  • hsh (Hash<#to_s,Object>)
  • sparse_key (#to_s)

Returns:

  • (Object)


127
128
129
# File 'lib/sparsify/utility_methods.rb', line 127

def sparse_get(hsh, sparse_key, options = {})
  sparse_fetch(hsh, sparse_key, options) { nil }
end

#unsparse(hsh, options = {}) ⇒ Hash<String,Object>

Returns a deeply-nested version of the given sparse hash

Parameters:

  • hsh (Hash<#to_s,Object>)

Returns:

  • (Hash<String,Object>)


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/sparsify/utility_methods.rb', line 58

def unsparse(hsh, options = {})
  separator = options.fetch(:separator, DEFAULT_SEPARATOR)
  hsh.each_with_object({}) do |(k, v), memo|
    current = memo
    key = escaped_split(k, separator)
    up_next = partial = key.shift
    until key.size.zero?
      up_next = key.shift
      up_next = up_next.to_i if (up_next =~ /\A[0-9]+\Z/)
      current = (current[partial] ||= (up_next.kind_of?(Integer) ? [] : {}))
      case up_next
      when Integer then raise KeyError unless current.kind_of?(Array)
      else              raise KeyError unless current.kind_of?(Hash)
      end
      partial = up_next
    end
    current[up_next] = v
  end
end