Module: DbSchema::Utils

Defined in:
lib/db_schema/utils.rb

Class Method Summary collapse

Class Method Details

.delete_at(hash, *keys) ⇒ Object



23
24
25
26
27
# File 'lib/db_schema/utils.rb', line 23

def delete_at(hash, *keys)
  keys.map do |key|
    hash.delete(key)
  end
end

.filter_by_class(array, klass) ⇒ Object



59
60
61
62
63
# File 'lib/db_schema/utils.rb', line 59

def filter_by_class(array, klass)
  array.select do |element|
    element.is_a?(klass)
  end
end

.filter_by_keys(hash, *needed_keys) ⇒ Object



13
14
15
16
17
18
19
20
21
# File 'lib/db_schema/utils.rb', line 13

def filter_by_keys(hash, *needed_keys)
  hash.reduce({}) do |final_hash, (key, value)|
    if needed_keys.include?(key)
      final_hash.merge(key => value)
    else
      final_hash
    end
  end
end

.remove_nil_values(hash) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/db_schema/utils.rb', line 37

def remove_nil_values(hash)
  hash.reduce({}) do |new_hash, (key, value)|
    if value.nil?
      new_hash
    else
      new_hash.merge(key => value)
    end
  end
end

.rename_keys(hash, mapping = {}) ⇒ Object



4
5
6
7
8
9
10
11
# File 'lib/db_schema/utils.rb', line 4

def rename_keys(hash, mapping = {})
  hash.reduce({}) do |final_hash, (key, value)|
    new_key = mapping.fetch(key, key)
    final_hash.merge(new_key => value)
  end.tap do |final_hash|
    yield(final_hash) if block_given?
  end
end

.sort_by_class(array, sorted_classes) ⇒ Object



53
54
55
56
57
# File 'lib/db_schema/utils.rb', line 53

def sort_by_class(array, sorted_classes)
  sorted_classes.flat_map do |klass|
    array.select { |object| object.is_a?(klass) }
  end
end

.symbolize_keys(hash) ⇒ Object



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

def symbolize_keys(hash)
  return hash unless hash.is_a?(Hash)

  hash.reduce({}) do |new_hash, (key, value)|
    new_hash.merge(key.to_sym => symbolize_keys(value))
  end
end

.to_hash(array, attribute) ⇒ Object



47
48
49
50
51
# File 'lib/db_schema/utils.rb', line 47

def to_hash(array, attribute)
  array.reduce({}) do |hash, object|
    hash.merge(object.public_send(attribute) => object)
  end
end