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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
|
# Generic extensions of the language
class MutableNumber
attr_accessor :value
def initialize(n=0)
@value = n
end
def add(n=1) @value += n end
def sub(n=1) @value -= n end
def set(n) @value = n end
end
class Array
def wrap(n)
# TODO: this can be done better...
n.times { push shift }
end
def cdr(n = 1)
self[n .. -1]
end
alias car first
def sh
map do |x|
if x.respond_to? :path
x.path.to_s
else
x.to_s
end.sh
end.join(" ")
end
end
class String
def clear
self.replace("")
end
if RUBY_VERSION < '1.9'
def ord
self[0]
end
end
def ascii_only()
gsub(/[^!-~\s]/, '*')
end
def ascii_only_if(bool)
bool ? ascii_only : dup
end
def from_first(str)
self.include?(str) ? self [ self.index(str) + str.size .. -1 ] : nil
end
def from_last(str)
self.include?(str) ? self [ self.rindex(str) + str.size .. -1 ] : nil
end
def split_at_last_dot()
if ix = self.rindex('.')
return self[0...ix], self[ix+1..-1]
else
return self, ''
end
end
def before_last(str)
self.include?(str) ? self [ 0 .. rindex(str) - str.size ] : self
end
def filetype()
Directory::Entry::MIMETYPES[self] || 'unknown'
end
## encodes a string for the shell.
## peter's song.mp3 -> 'peter'\''s song.mp3'
##
## system("mplayer #{ ~some_video_file }")
def bash_escape
"'#{bash_escape_no_quotes}'"
end
def bash_escape_no_quotes
"#{ gsub("'", "'\\\\''") }"
end
alias ~ bash_escape
alias sh bash_escape
end
class Numeric
def limit(max, min = 0)
self < min ? min : (self > max ? max : self)
end
def bytes(space = true, n_round = 2)
n = 1024
a = %w(B K M G T Y)
i = 0
flt = self.to_f
while flt > n and i < a.length - 1
flt /= n
i += 1
end
# flt = flt.round(n_round)
r = 10 ** n_round
flt *= r
flt = flt.round.to_f / r
int = flt.to_i
flt = int if int == flt
return flt.to_s + (space ? ' ' + a[i] : a[i])
end
end
class Dir
def self.number_of_files(*dirs)
n = 0
dirs.each do |entry|
if File.directory?(entry)
n += 1 + number_of_files(*(Dir.new(entry).to_a - ['.', '..']).map\
{|x| File.join entry, x } )
else
n += 1
end
end
return n
end
end
class File::Stat
MODES_HASH = {
'0' => '---',
'1' => '--x',
'2' => '-w-',
'3' => '-wx',
'4' => 'r--',
'5' => 'r-x',
'6' => 'rw-',
'7' => 'rwx'
}
def modestr
if symlink?
result = 'l'
elsif directory?
result = 'd'
else
result = '-'
end
s = ("%o" % mode)[-3..-1]
for m in s.each_char
result << MODES_HASH[m]
end
result
end
end
class Object; def or(value) self end end
class NilClass; def or(value) value end end
|