# # # = Utilities for Jeeves # # == human_size etc # # Author:: Robert Sharp # Copyright:: Copyright (c) 2013 Robert Sharp # License:: Open Software Licence v3.0 # # This software is licensed for use under the Open Software Licence v. 3.0 # The terms of this licence can be found at http://www.opensource.org/licenses/osl-3.0.php # and in the file copyright.txt. Under the terms of this licence, all derivative works # must themselves be licensed under the Open Software Licence v. 3.0 # # # require 'colored' module Jeeves Kb = 1 * 1000 Mb = Kb * Kb Gb = Mb * Kb Tb = Gb * Kb def Jeeves.human_size(size_in_k) size = size_in_k * Kb case when size < Mb then '%.1f KB' % (size_in_k) when size < Gb then '%.1f MB' % (size_in_k / Kb) when size < Tb then '%.1f GB' % (size_in_k / Mb) else '%.1f TB' % (size_in_k / Gb) end.sub('.0', '') rescue nil end def Jeeves.hrs_mins(secs) mins = secs / 60 hours = mins /60 mins -= hours * 60 mstr = "%02d" % mins units = hours > 1 ? 'hrs' : 'hr' return "#{hours}#{units}#{mstr}" end def Jeeves.tabulate(cols, header, data, colours=nil) data_s = Array.new data.each do |row| row_s = [] row.each do |cell| row_s << cell.to_s end data_s << row_s end data = data_s methods = Array.new(cols.length, :ljust) method_lup = {'l'=>:ljust, 'r'=>:rjust, 'c'=>:center} col_re = /^(\*|[0-9]+)([lrc]{0,1})$/ # need to get column widths from header and data cols.each_index do |col_index| if tokens = col_re.match(cols[col_index]) then if tokens[1] == '*' then # work out the column width cols[col_index] = header[col_index].length data.each do |row| cols[col_index] = row[col_index].length if row[col_index].length >= cols[col_index] end else cols[col_index] = tokens[1].to_i end # and add the justification method #puts tokens.inspect methods[col_index] = method_lup[tokens[2]] unless tokens[2] == '' end # if end # cols.each_index block #puts cols.inspect fstr = String.new header.each_index {|hdi| fstr << (sprintf header[hdi].send(methods[hdi], cols[hdi]).bold + ' ')} puts fstr data.each_index do |row_ind| fstr = String.new row = data[row_ind] row.each_index {|ri| fstr << (sprintf row[ri].send(methods[ri], cols[ri]) + ' ')} fstr = fstr.send(colours[row_ind]) unless colours.nil? || colours[row_ind].nil? puts fstr end end # rename a file by appending a random string to the basename # def Jeeves.rename(path) dir_name = File.dirname(path) extname = File.extname(path) root_basename = File.basename(path, extname) loop_count = 0 # catch a loop while block_given? ? yield(path) : FileTest.exists?(path) loop_count += 1 path = nil break if loop_count > 10 # oh dear, got one already. need to add something to the name randname = Kernel.rand(10000).to_s basename = root_basename + '_' + randname + extname path = File.join(dir_name, basename) end return path end end