class Object

Public Instance Methods

string_to_sortable_numeric(string) click to toggle source

rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity rubocop:enable Style/AsciiComments

# File lib/helpers/transform_to_sortable_numeric.rb, line 41
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
throws?(exception) { || ... } click to toggle source

Returns a Boolean for whether the block raises the Exception expected

throws?(StandardError) { raise }

> true

throws?(NameError) { raise NameError }

> true

throws?(NoMethodError) { raise NameError }

> false

throws?(StandardError) { 'foo' }

> false

# File lib/helpers/throws.rb, line 14
def throws?(exception)
  yield
  false
rescue StandardError => e
  e.is_a? exception
end
time_to_sortable_numeric(time) click to toggle source
# 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/MethodLength, 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