class Object
Public Instance Methods
flatten_keys_of(input, keys = [], output = {}, flattener: ->(*k) { k }
click to toggle source
refactored from stackoverflow.com/a/23861946/2884386
# File lib/helpers/flatten_keys_of.rb, line 27 def flatten_keys_of(input, keys = [], output = {}, flattener: ->(*k) { k }, flatten_arrays: false) if input.is_a?(Hash) input.each do |key, value| flatten_keys_of( value, keys + Array.wrap(key), output, flattener: flattener, flatten_arrays: flatten_arrays ) end elsif input.is_a?(Array) && flatten_arrays input.each_with_index do |value, index| flatten_keys_of( value, keys + Array.wrap(index), output, flattener: flattener, flatten_arrays: flatten_arrays ) end else return output.merge!(flattener.call(*keys) => input) end output end
string_to_sortable_numeric(string)
click to toggle source
rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
# File lib/helpers/transform_to_sortable_numeric.rb, line 40 def string_to_sortable_numeric(string) string # 'aB09ü' .split('') # ["a", "B", "0", "9", "ü"] .map { |char| char.ord.to_s.rjust(3, '0') } # ["097", "066", "048", "057", "252"] .insert(1, '.') # ["097", ".", "066", "048", "057", "252"] .reduce(&:concat) # "097.066048057252" .to_r # (24266512014313/250000000000) end
time_to_sortable_numeric(time)
click to toggle source
rubocop:enable Style/AsciiComments
# File lib/helpers/transform_to_sortable_numeric.rb, line 50 def time_to_sortable_numeric(time) # https://stackoverflow.com/a/30604935/2884386 (time.utc.to_f * 1000).round end
transform_to_sortable_numeric(value)
click to toggle source
rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
# File lib/helpers/transform_to_sortable_numeric.rb, line 17 def transform_to_sortable_numeric(value) # https://www.justinweiss.com/articles/4-simple-memoization-patterns-in-ruby-and-one-gem/#and-what-about-parameters @sortable_numeric ||= Hash.new do |h, key| h[key] = if key.is_a?(Numeric) key elsif key == true 1 elsif key == false 0 elsif key.is_a?(String) || key.is_a?(Symbol) string_to_sortable_numeric(key.to_s) elsif key.is_a?(Date) time_to_sortable_numeric(Time.new(key.year, key.month, key.day, 0o0, 0o0, 0o0, 0)) elsif key.respond_to?(:to_time) time_to_sortable_numeric(key.to_time) else key end end @sortable_numeric[value] end