Module: CmAdmin::Utils
- Defined in:
- lib/cm_admin/utils.rb
Class Method Summary collapse
- .as_json_params(hash, key, tokens) ⇒ Object
-
.base(hash, key, tokens) ⇒ Object
recursive.
- .deserialize_csv_columns(list, method) ⇒ Object
- .flatten_hash(hash, prefix = "", separator = "_") ⇒ Object
- .recursive_hash ⇒ Object
- .serialize_csv_columns(*columns, **hashes) ⇒ Object
Class Method Details
.as_json_params(hash, key, tokens) ⇒ Object
[View source]
29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/cm_admin/utils.rb', line 29 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
53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/cm_admin/utils.rb', line 53 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
[View source]
14 15 16 17 18 19 20 |
# File 'lib/cm_admin/utils.rb', line 14 def deserialize_csv_columns(list, method) # Does the opposite operation of serialize_csv_columns 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
[View source]
42 43 44 45 46 47 48 49 50 51 |
# File 'lib/cm_admin/utils.rb', line 42 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_hash ⇒ Object
[View source]
22 23 24 25 26 27 |
# File 'lib/cm_admin/utils.rb', line 22 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
[View source]
3 4 5 6 7 8 9 10 11 12 |
# File 'lib/cm_admin/utils.rb', line 3 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 CmAdmin::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 |