Module: Shugoi::Utils

Defined in:
lib/shugoi/utils.rb

Class Method Summary collapse

Class Method Details

.base36_decode(str) ⇒ Object



35
36
37
# File 'lib/shugoi/utils.rb', line 35

def base36_decode(str)
  str.to_s.to_i(36)
end

.base36_encode(num) ⇒ Object



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

def base36_encode(num)
  return "0" if num.zero?
  alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"
  out = +""
  n = num
  while n.positive?
    n, r = n.divmod(36)
    out.prepend(alphabet[r])
  end
  out
end

.escape_html(s) ⇒ Object



65
66
67
68
69
70
71
72
# File 'lib/shugoi/utils.rb', line 65

def escape_html(s)
  s.to_s
    .gsub("&", "&")
    .gsub("<", "&lt;")
    .gsub(">", "&gt;")
    .gsub('"', "&quot;")
    .gsub("'", "&#39;")
end

.escape_json_string(s) ⇒ Object



61
62
63
# File 'lib/shugoi/utils.rb', line 61

def escape_json_string(s)
  JSON.generate(s.to_s)[1..-2]
end

.hmac_hex(secret, payload) ⇒ Object



15
16
17
# File 'lib/shugoi/utils.rb', line 15

def hmac_hex(secret, payload)
  OpenSSL::HMAC.hexdigest("SHA256", secret.to_s, payload.to_s)
end

.leading_zero_bits(hex_digest) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/shugoi/utils.rb', line 39

def leading_zero_bits(hex_digest)
  leading = 0
  hex_digest.each_char do |c|
    nib = c.to_i(16)
    if nib.zero?
      leading += 4
      next
    end
    leading += (nib & 8) != 0 ? 0 : (nib & 4) != 0 ? 1 : (nib & 2) != 0 ? 2 : 3
    break
  end
  leading
end

.now_msObject



53
54
55
# File 'lib/shugoi/utils.rb', line 53

def now_ms
  (Time.now.to_f * 1000).to_i
end

.now_secObject



57
58
59
# File 'lib/shugoi/utils.rb', line 57

def now_sec
  Time.now.to_i
end

.secure_equals(a, b) ⇒ Object



9
10
11
12
13
# File 'lib/shugoi/utils.rb', line 9

def secure_equals(a, b)
  return false unless a.is_a?(String) && b.is_a?(String)
  return false unless a.bytesize == b.bytesize
  OpenSSL.fixed_length_secure_compare(a, b)
end

.sha256_hex(str) ⇒ Object



19
20
21
# File 'lib/shugoi/utils.rb', line 19

def sha256_hex(str)
  OpenSSL::Digest::SHA256.hexdigest(str.to_s)
end