-
Notifications
You must be signed in to change notification settings - Fork 5
/
utils.rb
135 lines (118 loc) · 2.49 KB
/
utils.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def show_and_do(str)
print str.yellow
show_wait_spinner do
yield
end
puts 'Done!'.green
end
class NilClass
def blank?
true
end
end
class FalseClass
def blank?
true
end
end
class TrueClass
# true.blank? # => false
def blank?
false
end
end
class Array
# [].blank? # => true
# [1,2,3].blank? # => false
alias_method :blank?, :empty?
end
class Hash
# {}.blank? # => true
# { key: 'value' }.blank? # => false
alias_method :blank?, :empty?
end
class String
def colorize(color_code)
"\e[#{color_code}m#{self}\e[0m"
end
def red
colorize(31)
end
def green
colorize(32)
end
def yellow
colorize(33)
end
def blue
colorize(34)
end
def pink
colorize(35)
end
def light_blue
colorize(36)
end
BLANK_RE = /\A[[:space:]]*\z/
# A string is blank if it's empty or contains whitespaces only:
#
# ''.blank? # => true
# ' '.blank? # => true
# "\t\n\r".blank? # => true
# ' blah '.blank? # => false
#
# Unicode whitespace is supported:
#
# "\u00a0".blank? # => true
#
def blank?
# The regexp that matches blank strings is expensive. For the case of empty
# strings we can speed up this method (~3.5x) with an empty? call. The
# penalty for the rest of strings is marginal.
empty? || BLANK_RE.match?(self)
end
end
def camelcase(str)
str.split('-').collect(&:capitalize).join
end
def kebabcase(str)
str.gsub(/([A-Z]+)([A-Z][a-z])/, '\1-\2').
gsub(/([a-z\d])([A-Z])/, '\1-\2').
tr('_', '-').
gsub(/\s/, '-').
gsub(/__+/, '-').
downcase
end
def to_valid_file_name(str)
kebabcase(str).gsub(%r{/[\x00\/\\:\*\?\"<>\|]/}, '-')
end
def yesno
case $stdin.getch
when 'Y', 'y' then 't'
when 'N', 'n' then 'f'
when 'A', 'a' then 'a'
else
puts 'Invalid character.'
puts 'Type Y for yes or N for no.'
yesno
end
end
def clear_console
system('cls') || system('clear')
end
def show_wait_spinner(fps = 10)
chars = %w[| / - \\]
delay = 1.0 / fps
iter = 0
spinner = Thread.new do
while iter
print chars[(iter += 1) % chars.length]
sleep delay
print "\b"
end
end
yield.tap do
iter = false
spinner.join
end
end