Module: ALib::Util

Defined in:
lib/alib.rb,
lib/alib-0.3.1.rb

Overview

the utility module is a namespace for things which otherwise wouldn’t have a home. the methods of Util can be used as module methods or included into a class and then used as instance OR class methods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.append_features(c) ⇒ Object

–}}}



46
47
48
49
50
51
# File 'lib/alib.rb', line 46

def append_features c
#--{{{
  super
  c.extend self 
#--}}}  
end

.export(*syms) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/alib.rb', line 37

def export(*syms)
#--{{{
  syms.each do |sym|
    sym = "#{ sym }".intern
    module_function sym 
    public sym
  end
#--}}}
end

Instance Method Details

#alive(pid) ⇒ Object Also known as: alive?

returns true if pid is running, false otherwise



207
208
209
210
211
212
213
214
215
216
217
# File 'lib/alib.rb', line 207

def alive pid
#--{{{
  pid = Integer("#{ pid }")
  begin
    Process::kill 0, pid
    true
  rescue Errno::ESRCH
    false
  end
#--}}}
end

#argv_split(argv) ⇒ Object

pop of options from an arglist



677
678
679
680
681
682
683
684
685
# File 'lib/alib.rb', line 677

def argv_split(argv)
#--{{{
  args = argv
  opts = args.pop if Hash === args.last
  puts "args : #{ args.inspect }"
  puts "opts : #{ opts.inspect }"
  [args, opts]
#--}}}
end

#atoi(s, opts = {}) ⇒ Object

convert a string to an integer



809
810
811
812
813
# File 'lib/alib.rb', line 809

def atoi(s, opts = {})
#--{{{
  strtod("#{ s }".gsub(%r/^0+/,''), 'base' => 10)
#--}}}
end

#attempt(label = 'attempt') ⇒ Object

initiates a catch block to do ‘something’. if the method try_again! is called the block is done over - if the method give_up! is called the block is aborted. calls to attempt may be nested.



589
590
591
592
593
594
595
596
# File 'lib/alib.rb', line 589

def attempt label = 'attempt'
#--{{{
  ret = nil
  n_attempts = 0
  loop{ break unless catch("#{ label }"){ ret = yield(n_attempts += 1) } == 'try_again' }
  ret
#--}}}
end

#btrace(e) ⇒ Object

format exception backtrace as string



437
438
439
440
441
# File 'lib/alib.rb', line 437

def btrace e
#--{{{
  (e.backtrace or []).join("\n")
#--}}}
end

#columnize(buf, opts = {}) ⇒ Object

wrap a string using options width (default 80) and indent using the indent option (default 0)



542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/alib.rb', line 542

def columnize buf, opts = {}
#--{{{
  width = Util::getopt 'width', opts, 80
  indent = Util::getopt 'indent', opts
  indent = Fixnum === indent ? (' ' * indent) : "#{ indent }"
  column = []
  words = buf.split %r/\s+/o
  row = "#{ indent }"
  while((word = words.shift))
    if((row.size + word.size) < (width - 1))
      row << word
    else
      column << row
      row = "#{ indent }"
      row << word
    end
    row << ' ' unless row.size == (width - 1)
  end
  column << row unless row.strip.empty?
  column.join "\n"
#--}}}
end

#defval(var, opts = {}) ⇒ Object

search for a default value for ‘var’ using

* DEFAULT_VAR 
* self.class.var

returning the option default, or nil



571
572
573
574
575
576
577
578
579
580
581
582
# File 'lib/alib.rb', line 571

def defval var, opts = {} 
#--{{{  
  default = Util::getopt 'default', opts, nil
  v = "#{ var }"
  c0, c1 = "DEFAULT_#{ v }".upcase, "#{ v }".upcase
  begin 
    klass.send(v) || klass.const_get(c0) || klass.const_get(c1)
  rescue NameError
    default
  end
#--}}}
end

#delopt(opt, hash, default = nil) ⇒ Object Also known as: delete_opt, extract_opt, extractopt, xopt

delete key in hash as key, then string of key, then intern of key - returning the value or, if key is not found, nil or default



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/alib.rb', line 180

def delopt opt, hash, default = nil
#--{{{
  keys = opt.respond_to?('each') ? opt : [opt]

  keys.each do |key|
    return hash.delete(key) if hash.has_key? key
    key = "#{ key }"
    return hash.delete(key) if hash.has_key? key
    key = key.intern
    return hash.delete(key) if hash.has_key? key
  end

  return default
#--}}}
end

#emsg(e) ⇒ Object

format exception as Logger class does - no backtrace



428
429
430
431
432
# File 'lib/alib.rb', line 428

def emsg e
#--{{{
  "#{ e.message } - (#{ e.class })"
#--}}}
end

#erreq(a, b) ⇒ Object

determine equality of two exceptions



455
456
457
458
459
460
461
# File 'lib/alib.rb', line 455

def erreq a, b
#--{{{
  a.class == b.class and
  a.message == b.message and
  a.backtrace == b.backtrace
#--}}}
end

#errmsg(e) ⇒ Object

format exception as Logger class does - with backtrace



446
447
448
449
450
# File 'lib/alib.rb', line 446

def errmsg e
#--{{{
  emsg(e) << "\n" << btrace(e)
#--}}}
end

#escape(s, char, esc) ⇒ Object

new copy of s with any occurances of char escaped with esc



342
343
344
345
346
# File 'lib/alib.rb', line 342

def escape s, char, esc
#--{{{
  escape! "#{ s }", char, esc
#--}}}
end

#escape!(s, char, esc) ⇒ Object

escapes any occurances of char in s with esc modifying s inplace



329
330
331
332
333
334
335
336
337
# File 'lib/alib.rb', line 329

def escape! s, char, esc
#--{{{
  # re = %r/([#{ 0x5c.chr << esc }]*)#{ char }/
  re = %r/([#{ Regexp::quote esc }]*)#{ Regexp::quote char }/
  s.gsub!(re) do
    (($1.size % 2 == 0) ? ($1 << esc) : $1) + char 
  end
#--}}}
end

#exec(*args, &block) ⇒ Object

an quiet exec



366
367
368
369
370
371
372
373
374
375
376
# File 'lib/alib.rb', line 366

def exec(*args, &block)
#--{{{
  begin
    verbose = $VERBOSE
    $VERBOSE = nil
    Kernel::exec(*args, &block)
  ensure
    $VERBOSE = verbose
  end
#--}}}
end

#expand(string, opts = {}) ⇒ Object



892
893
894
895
896
# File 'lib/alib.rb', line 892

def expand string, opts = {}
#--{{{
  Util::expand! string.dup, opts
#--}}}
end

#expand!(string, vars = {}) ⇒ Object

expand variables in a string destructively (to the string)



871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
# File 'lib/alib.rb', line 871

def expand! string, vars = {} 
#--{{{
  loop do
    changed = false
    vars.each do |var, value|
      var.gsub! %r/[^a-zA-Z0-9_]/, ''
      [ 
        %r/\$#{ var }\b/, 
        %r/\@#{ var }\b/, 
        %r/\${\s*#{ var }\s*}/, 
        %r/\@{\s*#{ var }\s*}/ 
      ].each do |pat|
        changed = string.gsub! pat, "#{ value }"
      end
    end
    break unless changed
  end
  string
#--}}}
end

#find(*a, &b) ⇒ Object

shortcut to Find2



638
639
640
641
642
643
# File 'lib/alib.rb', line 638

def find(*a, &b)
#--{{{
  a << '.' if a.empty?
  Find2::find(*a, &b)
#--}}}
end

#find2(*a, &b) ⇒ Object

shortcut to Find2



648
649
650
651
652
653
# File 'lib/alib.rb', line 648

def find2(*a, &b)
#--{{{
  a << '.' if a.empty?
  Find2::find2(*a, &b)
#--}}}
end

#fork(*args, &block) ⇒ Object

a quiet fork



351
352
353
354
355
356
357
358
359
360
361
# File 'lib/alib.rb', line 351

def fork(*args, &block)
#--{{{
  begin
    verbose = $VERBOSE
    $VERBOSE = nil
    Process::fork(*args, &block)
  ensure
    $VERBOSE = verbose
  end
#--}}}
end

#getopt(opt, hash, default = nil) ⇒ Object Also known as: get_opt

look up key in hash as key, then string of key, then intern of key - returning the value or, if key is not found, nil or default



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/alib.rb', line 132

def getopt opt, hash, default = nil
#--{{{
  keys = opt.respond_to?('each') ? opt : [opt]

  keys.each do |key|
    return hash[key] if hash.has_key? key
    key = "#{ key }"
    return hash[key] if hash.has_key? key
    key = key.intern
    return hash[key] if hash.has_key? key
  end

  return default
#--}}}
end

#give_up!(label = 'attempt') ⇒ Object Also known as: giveup!, give_up

see attempt



612
613
614
615
616
# File 'lib/alib.rb', line 612

def give_up! label = 'attempt'
#--{{{
  throw "#{ label }", 'give_up'
#--}}}
end

#hashify(*hashes) ⇒ Object

collect n hashed into one hash - later keys overried earlier keys



122
123
124
125
126
# File 'lib/alib.rb', line 122

def hashify(*hashes)
#--{{{
  hashes.inject(accum={}){|accum,hash| accum.update hash}
#--}}}
end

#hasopt(opt, hash, default = false) ⇒ Object Also known as: has_opt, hasopt?, has_opt?

determine if a key, key.to_s, or key.to_s.intern is in hash see getopt



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/alib.rb', line 154

def hasopt opt, hash, default = false 
#--{{{
  keys = opt.respond_to?('each') ? opt : [opt]

  keys.each do |key|
    return key if hash.has_key? key
    key = "#{ key }"
    return key if hash.has_key? key
    key = key.intern
    return key if hash.has_key? key
  end

  return default
#--}}}
end

#hms(seconds) ⇒ Object

explode a



858
859
860
861
862
863
864
865
866
# File 'lib/alib.rb', line 858

def hms seconds
#--{{{
  [
    Integer(seconds / 3600),
    Integer((seconds % 3600) / 60),
    Float((seconds % 3600) / 60.0)
  ]
#--}}}
end

#hostObject

lookup, and cache, the host (first bit of hostname quad)



419
420
421
422
423
# File 'lib/alib.rb', line 419

def host
#--{{{
  @__host__ ||= hostname.gsub(%r/\..*$/o,'')
#--}}}
end

#hostnameObject

lookup, and cache, the hostname



410
411
412
413
414
# File 'lib/alib.rb', line 410

def hostname
#--{{{
  @__hostname__ ||= Socket::gethostname
#--}}}
end

#klassObject

self.class



99
100
101
102
103
# File 'lib/alib.rb', line 99

def klass
#--{{{
  self.class
#--}}}
end

#klass_stamp(hierachy, *a, &b) ⇒ Object

creates a class by class name



623
624
625
626
627
628
629
630
631
632
633
# File 'lib/alib.rb', line 623

def klass_stamp(hierachy, *a, &b)
#--{{{
  ancestors = hierachy.split(%r/::/)
  parent = Object
  while((child = ancestors.shift))
    klass = parent.const_get child
    parent = klass
  end
  klass::new(*a, &b)
#--}}}
end

#maim(pid, opts = {}) ⇒ Object

brutally shut down a process. opts can contain the keys ‘signals’ which should be a list of signals used to send to the process and the key ‘suspend’ which is the amount of time to wait after firing each signal before seeing if the process is dead. the defaults are %w(TERM QUIT KILL) and 4 respectively



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/alib.rb', line 227

def maim(pid, opts = {})
#--{{{
  sigs = Util::getopt 'signals', opts, %w(SIGTERM SIGQUIT SIGKILL)
  suspend = Util::getopt 'suspend', opts, 4
  pid = Integer("#{ pid }")
  existed = false
  sigs.each do |sig|
    begin
      Process::kill(sig, pid)
      existed = true 
    rescue Errno::ESRCH
      unless existed
        return nil 
      else
        return true 
      end
    end
    return true unless alive?(pid)
    sleep suspend
    return true unless alive?(pid)
  end
  return(not alive?(pid)) 
#--}}}
end

#mcp(obj) ⇒ Object

marshal’d ‘deep’ copy of obj



90
91
92
93
94
# File 'lib/alib.rb', line 90

def mcp obj
#--{{{
  Marshal.load(Marshal.dump(obj))
#--}}}
end

#mdObject

declare multi-dimensional arrays as in md



911
912
913
914
915
916
# File 'lib/alib.rb', line 911

def md
#--{{{
  @__md__ ||=
    lambda{|*ds| Array::new(ds.shift||0).map{md[*ds] unless ds.empty?}}
#--}}}
end

#optfilter(*list) ⇒ Object

pull out options from arglist



667
668
669
670
671
672
# File 'lib/alib.rb', line 667

def optfilter(*list)
#--{{{
  args, opts = [ list ].flatten.partition{|item| not Hash === item}
  [args, Util::hashify(*opts)]
#--}}}
end

#prognamObject

the basename of $0



81
82
83
84
85
# File 'lib/alib.rb', line 81

def prognam
#--{{{
  File::basename $0
#--}}}
end

#pruneObject

shortcut to Find2.prune



658
659
660
661
662
# File 'lib/alib.rb', line 658

def prune
    #--{{{
  Find2.prune
    #--}}}
end

#rangemod(n, ir) ⇒ Object

bin a integer into a int range using modulo logic



818
819
820
821
822
823
824
825
826
827
828
829
# File 'lib/alib.rb', line 818

def rangemod n, ir
#--{{{
  a, b = Integer(ir.first), Integer(ir.last)
  a, b = b, a if a >= b
  exclusive = ir.exclude_end?
  size = b - a 
  size += 1 unless exclusive
  offset = a - 0
  x = (n + offset).modulo size
  x += offset
#--}}}
end

#realpath(path) ⇒ Object

File::expand_path + link resolution



108
109
110
111
112
113
114
115
116
117
# File 'lib/alib.rb', line 108

def realpath path
#--{{{
  path = File::expand_path "#{ path }"
  begin
    Pathname.new(path).realpath.to_s
  rescue Errno::ENOENT, Errno::ENOTDIR
    path
  end
#--}}}
end

#require_version(version) ⇒ Object

requires a certain version of ruby or higher

require_version '1.8.0'


57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/alib.rb', line 57

def require_version version
#--{{{
  major, minor, teeny = "#{ version }".split(%r/\./o).map{|n| Integer(n)}
  required = "#{ major }.#{ minor }.#{ teeny }"
  _major, _minor, _teeny = 
    %w( MAJOR MINOR TEENY ).map{|k| Integer(::Config::CONFIG[k])}
  actual = "#{ _major }.#{ _minor }.#{ _teeny }"
  unless _major > major  or _major == major and _minor >= minor 
    STDERR.puts("=" * 79)
    STDERR.puts "this program requires a ruby version >= <#{ required }>"
    STDERR.puts 
    STDERR.puts "you are currenlty running ruby version <#{ actual }>"
    STDERR.puts 
    STDERR.puts "possible problems which could cause this are:"
    STDERR.puts "  - improper PATH environment variable setting"
    STDERR.puts "  - ruby > <#{ required }> has not been installed"
    STDERR.puts("=" * 79)
    exit 1
  end
#--}}}
end

#spawn(cmd, opts = {}) ⇒ Object

a quiet system which succeeds or throws errors



396
397
398
399
400
401
402
403
404
405
# File 'lib/alib.rb', line 396

def spawn cmd, opts = {} 
#--{{{
  exitstatus = Util::getopt(%w( exitstatus exit_status status ), opts, 0)
  Util::system cmd
  status = $?.exitstatus
  raise "cmd <#{ cmd }> failed with <#{ status }>" unless 
    status == exitstatus
  status
#--}}}
end

#splitpath(path) ⇒ Object

split a path into dirname, basename, extension



690
691
692
693
694
695
696
# File 'lib/alib.rb', line 690

def splitpath path
#--{{{
  path = "#{ path }"
  dirname, basename = File::split path
  [ dirname, (%r/^([^\.]*)(.*)$/).match(basename)[1,2] ].flatten
#--}}}
end

#stamptime(string, opts = {}) ⇒ Object

TODO - review hack to fix Time::parse bug with ms and tz



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/alib.rb', line 300

def stamptime string, opts = {} 
#--{{{
  tz = string[ %r/-\d\d:\d\d\s*$/ ]
  time = nil
  if opts.empty? or tz
    u = string[%r/\.\d+/]
    string[%r/\.\d+/] = '' if u 
    time = Time::parse string
    time += u.to_f if u
  else
    local = Util::getopt 'local', opts, false 
    string = "#{ string }"
    pat = %r/^\s*(\d\d\d\d)-(\d\d)-(\d\d)[\s_tT]+(\d\d):(\d\d):(\d\d)(?:.(\d+))?\s*$/o
    match = pat.match string
    raise ArgumentError, "<#{ string.inspect }>" unless match
    yyyy,mm,dd,h,m,s,u = match.to_a[1..-1].map{|m| (m || 0).to_i}
    if local
      time = Time::local yyyy,mm,dd,h,m,s,u
    else
      time = Time::gm yyyy,mm,dd,h,m,s,u
    end
  end
  return time
#--}}}
end

#strtod(s, opts = {}) ⇒ Object

convert a string to an integer of any base



791
792
793
794
795
796
797
798
799
800
801
802
803
804
# File 'lib/alib.rb', line 791

def strtod(s, opts = {})
#--{{{
  base = Util::getopt 'base', opts, 10
  case base
    when 2
      s = "0b#{ s }" unless s =~ %r/^0b\d/
    when 8
      s = "0#{ s }" unless s =~ %r/^0\d/
    when 16 
      s = "0x#{ s }" unless s =~ %r/^0x\d/
  end
  Integer s
#--}}}
end

#system(*args, &block) ⇒ Object

a quiet system



381
382
383
384
385
386
387
388
389
390
391
# File 'lib/alib.rb', line 381

def system(*args, &block)
#--{{{
  begin
    verbose = $VERBOSE
    $VERBOSE = nil
    Kernel::system(*args, &block)
  ensure
    $VERBOSE = verbose
  end
#--}}}
end

#timestamp(arg = Time::now) ⇒ Object

YYYY-MM-DD hh:mm:ss.uuuuuu representation of time. if the option ‘nospace’ is true spaces are replaced with underscores/or the value of the nospace option - useful for constructing filenames



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/alib.rb', line 257

def timestamp arg = Time::now
#--{{{
  if Time === arg 
    arg.iso8601 2
  else
    opts =
      case arg
        when Hash
          opts = arg
        when Time
          {'time' => arg}
        else
          raise ArgumentError, "#{ arg.inspect } (#{ arg.class })"
      end
    time = Util::getopt 'time', opts, Time::now
    local = Util::getopt 'local', opts, false 
    nospace = Util::getopt('nospace', opts, Util::getopt('no_space', opts, false))
    dateonly = Util::getopt('dateonly', opts, Util::getopt('date_only', opts, false))
    time = time.utc unless local
    usec = "#{ time.usec }"
    usec << ('0' * (6 - usec.size)) if usec.size < 6 
    stamp =
    unless dateonly
      time.strftime('%Y-%m-%d %H:%M:%S.') << usec
    else
      time.strftime('%Y-%m-%d')
    end
    if nospace
      spc = TrueClass === nospace ? 'T' : "#{ nospace }"
      stamp.gsub! %r/\s+/, spc
    end
    stamp
  end
#--}}}
end

#tmpdir(*argv) ⇒ Object



485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/alib.rb', line 485

def tmpdir(*argv)
#--{{{
  args, opts = Util::optfilter argv
  retries = Util::getopt 'retries', opts, 42
  opts['dir'] ||= (args.first || Util::getopt('base', opts) || '.')
  d = nil
  retries.times do
    td = Util::tmpnam(opts)
    break if ((d = FileUtils::mkdir_p td rescue nil))
  end
  raise "surpassed max retries <#{ retries }>" unless d
  d = File::expand_path d
  if block_given?
    cwd = Dir::pwd
    begin
      Dir::chdir d
      yield [cwd,d]
    ensure
      Dir::chdir cwd if cwd
      Dir[File::join(d, "**")].each{|e| FileUtils::rm_rf e}
      FileUtils::rm_rf d
    end
  else
    at_exit{ FileUtils::rm_rf d }
    return d
  end
#--}}}
end

#tmpnam(opts = {}) ⇒ Object

generate a temporary filename for the directory dir using seed as a basename



467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'lib/alib.rb', line 467

def tmpnam opts = {} 
#--{{{
  dir = Util::getopt 'dir', opts, Dir::tmpdir
  seed = Util::getopt 'seed', opts, Util::prognam
  path = 
    "%s_%s_%s_%s_%d" % [
      Util::hostname, 
      seed,
      Process::pid, 
      Util::timestamp('nospace' => true),
      rand(101010)
    ] 
  dirname, basename = File::dirname(path), File::basename(path)
  tn = File::join(dir, dirname, basename.gsub(%r/[^0-9a-zA-Z]/,'_')).gsub(%r/\s+/, '_')
  File::expand_path tn
#--}}}
end

#try_again!(label = 'attempt') ⇒ Object Also known as: try_again, again!

see attempt



601
602
603
604
605
# File 'lib/alib.rb', line 601

def try_again! label = 'attempt'
#--{{{
  throw "#{ label }", 'try_again'
#--}}}
end

#uncache(file) ⇒ Object

make best effort to invalidate any inode caching done by nfs clients



517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
# File 'lib/alib.rb', line 517

def uncache file 
#--{{{
  refresh = nil
  begin
    is_a_file = File === file
    path = (is_a_file ? file.path : file.to_s) 
    stat = (is_a_file ? file.stat : File::stat(file.to_s)) 
    refresh = tmpnam(File::dirname(path))
    File::link path, refresh rescue File::symlink path, refresh
    File::chmod stat.mode, path
    File::utime stat.atime, stat.mtime, path
    open(File::dirname(path)){|d| d.fsync rescue nil}
  ensure 
    begin
      File::unlink refresh if refresh
    rescue Errno::ENOENT
    end
  end
#--}}}
end

#unindent(s) ⇒ Object



933
934
935
936
937
938
939
# File 'lib/alib.rb', line 933

def unindent s
#--{{{
  s = "#{ s }"
  Util::unindent! s
  s
#--}}}
end

#unindent!(s) ⇒ Object

find natural left margin of a here-doc and un-indent it



921
922
923
924
925
926
927
928
929
930
931
# File 'lib/alib.rb', line 921

def unindent! s
#--{{{
  indent = nil
  s.each do |line|
    next if line =~ %r/^\s*$/
    indent = line[%r/^\s*/] and break
  end
  s.gsub! %r/^#{ indent }/, "" if indent
  indent ? s : nil
#--}}}
end

#unzip(path, z_pat = nil) ⇒ Object Also known as: gunzip

unzip a file - return unzipped name



751
752
753
754
755
756
757
758
759
760
761
762
763
# File 'lib/alib.rb', line 751

def unzip path, z_pat = nil 
#--{{{
  z_pat ||= %r/\.(?:z|gz)$/io
  Util::spawn "gzip --force --decompress #{ path }" if zipped?(path, z_pat)
  #Util::spawn "gzip --force --decompress #{ path }"
  uzn = Util::unzipped_name path, z_pat 
  if block_given?
    yield uzn
  else
    uzn
  end
#--}}}
end

#unzipped(path, z_pat = %r/\.(?:z|gz)$/io) ⇒ Object

handle a pathname after unzipping (iff needed)



701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
# File 'lib/alib.rb', line 701

def unzipped path, z_pat = %r/\.(?:z|gz)$/io
#--{{{
  zipped = zipped?(path, z_pat)
  unless zipped
    yield path
  else
    unzipped = unzip path
    begin
      yield unzipped
    ensure
      zip unzipped
    end
  end
#--}}}
end

#unzipped_name(path, z_pat = nil) ⇒ Object

return the unzipped name of a path



770
771
772
773
774
775
# File 'lib/alib.rb', line 770

def unzipped_name path, z_pat = nil 
#--{{{
  z_pat ||= %r/\.(?:z|gz)$/io
  path.gsub z_pat, ''
#--}}}
end

#which_rubyObject

determine path of current ruby interpreter (argv in c)



901
902
903
904
905
906
# File 'lib/alib.rb', line 901

def which_ruby
#--{{{
  c = ::Config::CONFIG
  File::join(c['bindir'], c['ruby_install_name']) << c['EXEEXT']
#--}}}
end

#zip(path, z_ext = nil) ⇒ Object Also known as: gzip

zip a file - return zipped name



720
721
722
723
724
725
726
727
728
729
730
731
732
733
# File 'lib/alib.rb', line 720

def zip path, z_ext = nil 
#--{{{
  z_ext ||= '.gz'
  z_ext.gsub! %r/^\s*\.+/, '.'
  Util::spawn "gzip --suffix #{ z_ext } --force #{ path }"
  zipped = "#{ path }#{ z_ext }"
  raise "could not create <#{ zipped }>" unless test ?e, zipped
  if block_given?
    yield zipped
  else
    zipped
  end
#--}}}
end

#zipped?(path, z_pat = %r/\.(?:z|gz)$/io) ⇒ Boolean Also known as: gzipped?

guess if a file is zipped based on pathname

Returns:

  • (Boolean)


780
781
782
783
784
# File 'lib/alib.rb', line 780

def zipped? path, z_pat = %r/\.(?:z|gz)$/io
#--{{{
  path =~ z_pat
#--}}}
end

#zipped_name(path, z_ext = nil) ⇒ Object

return the zipped name of a path



740
741
742
743
744
745
746
# File 'lib/alib.rb', line 740

def zipped_name path, z_ext = nil 
#--{{{
  z_ext ||= '.gz'
  z_ext.gsub! %r/^\s*\.+/, '.'
  "#{ path }#{ z_ext }"
#--}}}
end