Module: Elastictastic::Util

Extended by:
Util
Included in:
Util
Defined in:
lib/elastictastic/util.rb

Instance Method Summary collapse

Instance Method Details

#call_or_each(object, &block) ⇒ Object


37
38
39
40
41
42
43
# File 'lib/elastictastic/util.rb', line 37

def call_or_each(object, &block)
  if Array === object then object.each(&block)
  else
    block.call(object)
    object
  end
end

#call_or_map(object, &block) ⇒ Object


45
46
47
48
49
# File 'lib/elastictastic/util.rb', line 45

def call_or_map(object, &block)
  if Array === object then object.map(&block)
  else block.call(object)
  end
end

#deep_merge(l, r) ⇒ Object


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/elastictastic/util.rb', line 13

def deep_merge(l, r)
  if l.nil? then r
  elsif r.nil? then l
  elsif Hash === l && Hash === r
    {}.tap do |merged|
      (l.keys | r.keys).each do |key|
        merged[key] = deep_merge(l[key], r[key])
      end
    end
  elsif Array === l && Array === r then l + r
  elsif Array === l then l + [r]
  elsif Array === r then [l] + r
  else [l, r]
  end
end

#deep_stringify(hash) ⇒ Object


5
6
7
8
9
10
11
# File 'lib/elastictastic/util.rb', line 5

def deep_stringify(hash)
  {}.tap do |stringified|
    hash.each_pair do |key, value|
      stringified[key.to_s] = Hash === value ? deep_stringify(value) : value
    end
  end
end

#ensure_array(object) ⇒ Object


29
30
31
32
33
34
35
# File 'lib/elastictastic/util.rb', line 29

def ensure_array(object)
  case object
  when nil then []
  when Array then object
  else [object]
  end
end

#unflatten_hash(hash) ⇒ Object


51
52
53
54
55
56
57
58
59
60
61
# File 'lib/elastictastic/util.rb', line 51

def unflatten_hash(hash)
  {}.tap do |unflattened|
    hash.each_pair do |key, value|
      namespace = key.split('.')
      field_name = namespace.pop
      namespace.inject(unflattened) do |current, component|
        current[component] ||= {}
      end[field_name] = value
    end
  end
end