Module: Kerbi::Utils::Misc

Defined in:
lib/utils/misc.rb

Class Method Summary collapse

Class Method Details

.deep_hash_diff(hash_a, hash_b) ⇒ Object

Parameters:

  • hash_a (Hash)
  • hash_b (Hash)


44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/utils/misc.rb', line 44

def self.deep_hash_diff(hash_a, hash_b)
  (hash_a.keys | hash_b.keys).inject({}) do |diff, k|
    if hash_a[k] != hash_b[k]
      if hash_a[k].is_a?(Hash) && hash_b[k].is_a?(Hash)
        diff[k] = deep_hash_diff(hash_a[k], hash_b[k])
      else
        diff[k] = [hash_a[k], hash_b[k]]
      end
    end
    diff
  end
end

.flatten_hash(hash) ⇒ Hash

Turns a nested dict into a deep-keyed dict. For example {y: ā€˜zā€™} becomes ā€˜zā€™

Parameters:

  • hash (Hash)

    input nested dict

Returns:

  • (Hash)

    flattened dict



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/utils/misc.rb', line 28

def self.flatten_hash(hash)
  hash.each_with_object({}) do |(k, v), h|
    if v.is_a? Hash
      flatten_hash(v).map do |h_k, h_v|
        h["#{k}.#{h_k}".to_sym] = h_v
      end
    else
      h[k] = v
    end
  end
end

.one_to_array(item) ⇒ Object



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

def self.one_to_array(item)
  return [] if item.nil?
  if item.is_a?(Array)
    item
  else
    [item]
  end
end

.pretty_time_elapsed(other) ⇒ String

Parameters:

  • other (Time)

Returns:

  • (String)


61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/utils/misc.rb', line 61

def self.pretty_time_elapsed(other)
  a = (Time.now - other).to_i
  case a
  when 0 then 'just now'
  when 1 then 'a second ago'
  when 2..59 then a.to_s+' seconds ago'
  when 60..119 then 'a minute ago' #120 = 2 minutes
  when 120..3540 then (a/60).to_i.to_s+' minutes ago'
  when 3541..7100 then 'an hour ago' # 3600 = 1 hour
  when 7101..82800 then ((a+99)/3600).to_i.to_s+' hours ago'
  else other.to_s
  end
end

.real_files_for(*candidates) ⇒ Array

Given a list of filenames, returns the subset that are real files.

Parameters:

  • candidates (Array)

    filenames to try

Returns:

  • (Array)

    subset of candidate filenames that are real filenames



17
18
19
20
21
# File 'lib/utils/misc.rb', line 17

def self.real_files_for(*candidates)
  candidates.select do |fname|
    File.exists?(fname) && !Dir.exists?(fname)
  end
end