Module: HashOp::Filter

Defined in:
lib/hash_op/filter.rb

Class Method Summary collapse

Class Method Details

.filter(hashes, criteria = {}) ⇒ Array

Filters an array of hashes according to criteria on the values of each hash.

Example:

“‘ruby hashes = [

{ value: 123, regexp: "itsamatch", proc: "1+1" },
{ value: 123, regexp: "abcdef", proc: "1+2" },
{ value: 234, regexp: "abcdef", proc: "1+2" }

] HashOp::Filter.filter(hashes, { value: 123 })

> [

[0] {
    :proc => "1+1",
  :regexp => "itsamatch",
   :value => 123
},
[1] {
    :proc => "1+2",
  :regexp => "abcdef",
   :value => 123
}

] “‘



38
39
40
41
42
# File 'lib/hash_op/filter.rb', line 38

def filter(hashes, criteria = {})
  hashes.select do |item|
    match?(item, criteria)
  end
end

.filter_deep(hash, path, criteria = {}) ⇒ Hash

Applies ::filter on the value of an hash



55
56
57
58
59
60
61
# File 'lib/hash_op/filter.rb', line 55

def filter_deep(hash, path, criteria = {})
  array = HashOp::Deep.fetch hash, path
  raise "Can\'t filter hash at path \"#{path}\", value is not an array" unless array.is_a?(Array)

  filtered_array = filter(array, criteria)
  HashOp::Deep.merge hash, path, filtered_array
end

.match?(hash, criteria) ⇒ Boolean



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/hash_op/filter.rb', line 79

def match?(hash, criteria)
  unless hash.is_a?(Hash)
    fail ArgumentError, 'First argument must be an Hash'
  end
  return true if criteria.blank?

  criteria.map do |path, matching_object|
    value = HashOp::Deep.fetch(hash, path)
    case
    when matching_object.is_a?(Proc)
      matching_object.call(value)
    when matching_object.is_a?(Regexp)
      (value =~ matching_object).present?
    else value == matching_object
    end
  end.uniq == [true]
end