Module: SpotlightSearch::Utils

Defined in:
lib/spotlight_search/utils.rb

Class Method Summary collapse

Class Method Details

.as_json_params(hash, key, tokens) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/spotlight_search/utils.rb', line 37

def as_json_params(hash, key, tokens)
  hash.empty? && hash = { only: [], methods: [], include: recursive_hash }
  if tokens.empty?
    # base case
    hash[:methods] << key
  else
    # recursive case
    # hash[:associations] ||= {}
    hash[:include][key] = as_json_params(hash[:include][key], tokens.shift, tokens)
  end
  hash
end

.base(hash, key, tokens) ⇒ Object

recursive



24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/spotlight_search/utils.rb', line 24

def base(hash, key, tokens) # recursive
  hash.empty? && hash = { columns: [], associations: recursive_hash }
  if tokens.empty?
    # base case
    hash[:columns] << key
  else
    # recursive case
    # hash[:associations] ||= {}
    hash[:associations][key] = base(hash[:associations][key], tokens.shift, tokens)
  end
  hash
end

.deserialize_csv_columns(list, method) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/spotlight_search/utils.rb', line 16

def deserialize_csv_columns(list, method)
  # Does the opposite operation of the above
  list.reduce(recursive_hash) do |acc, item|
    tokens = item.to_s.split('/')
    send(method, acc, tokens.shift, tokens)
  end
end

.flatten_hash(hash, prefix = "", separator = "_") ⇒ Object



57
58
59
60
61
62
63
64
65
66
# File 'lib/spotlight_search/utils.rb', line 57

def flatten_hash(hash, prefix="", separator="_")
  hash.reduce({}) do |acc, item|
    case item[1]
    when Hash
      acc.merge(flatten_hash(item[1], "#{prefix}#{item[0]}#{separator}"))
    else
      acc.merge("#{prefix}#{item[0]}" => item[1])
    end
  end
end

.recursive_hashObject



50
51
52
53
54
55
# File 'lib/spotlight_search/utils.rb', line 50

def recursive_hash
  func = ->(h, k) { h[k] = Hash.new(&func) }
  # This hash creates a new hash, infinitely deep, whenever a value is not found
  # recursive_hash[:a][:b][:c][:d] will never fail
  Hash.new(&func)
end

.serialize_csv_columns(*columns, **hashes) ⇒ Object



5
6
7
8
9
10
11
12
13
14
# File 'lib/spotlight_search/utils.rb', line 5

def serialize_csv_columns(*columns, **hashes)
  # Turns an arbitrary list of args and kwargs into a list of params to be used in a form
  # For example, turns SpotlightSearch::Utils.serialize_csv_columns(:a, :b, c: [:d, e: :h], f: :g)
  # into [:a, :b, "c/d", "c/e/h", "f/g"]
  columns.map(&:to_s) + hashes.map do |key, value|
    serialize_csv_columns(*value).map do |column|
      "#{key}/#{column}"
    end
  end.reduce([], :+)
end