A motley collection of methods that Rudy loves to call!
Methods
public instance
Included modules
- Socket::Constants
Public instance methods
msg The message to return as a banner size One of: :normal (default), :huge colour a valid Returns a string with styling applying
# File lib/rudy/utils.rb, line 158 158: def banner(msg, size = :normal, colour = :black) 159: return unless msg 160: banners = { 161: :huge => Rudy::Utils.without_indent(%Q( 162: ======================================================= 163: ======================================================= 164: !!!!!!!!! %s !!!!!!!!! 165: ======================================================= 166: =======================================================)), 167: :normal => %Q(============ %s ============) 168: } 169: size = :normal unless banners.has_key?(size) 170: #colour = :black unless Drydock::Console.valid_colour?(colour) 171: size, colour = size.to_sym, colour.to_sym 172: sprintf(banners[size], msg).bright.att(:reverse) 173: end
Make a terminal bell chime
# File lib/rudy/utils.rb, line 98 98: def bell(chimes=1, logger=nil) 99: chimes ||= 0 100: return unless logger 101: chimed = chimes.to_i 102: logger.print "\a"*chimes if chimes > 0 && logger 103: true # be like Rudy.bug() 104: end
Have you seen that episode of The Cosby Show where Dizzy Gillespie… ah nevermind.
# File lib/rudy/utils.rb, line 107 107: def bug(bugid, logger=STDERR) 108: logger.puts "You have found a bug! If you want, you can email".color(:red) 109: logger.puts 'rudy@solutious.com'.color(:red).bright << " about it. It's bug ##{bugid}.".color(:red) 110: logger.puts "Continuing...".color(:red) 111: true # so we can string it together like: bug('1') && next if ... 112: end
Capture STDOUT or STDERR to prevent it from being printed.
capture(:stdout) do ... end
# File lib/rudy/utils.rb, line 236 236: def capture(stream) 237: #raise "We can only capture STDOUT or STDERR" unless stream == :stdout || stream == :stderr 238: begin 239: stream = stream.to_s 240: eval "$#{stream} = StringIO.new" 241: yield 242: result = eval("$#{stream}").read 243: ensure 244: eval("$#{stream} = #{stream.upcase}") 245: end 246: 247: result 248: end
Return the external IP address (the one seen by the internet)
# File lib/rudy/utils.rb, line 17 17: def external_ip_address 18: ip = nil 19: begin 20: %w{solutious.heroku.com/ip}.each do |sponge| 21: ipstr = Net::HTTP.get(URI.parse("http://#{sponge}")) || '' 22: ip = /([0-9]{1,3}\.){3}[0-9]{1,3}/.match(ipstr).to_s 23: break if ip && !ip.empty? 24: end 25: rescue SocketError, Errno::ETIMEDOUT => ex 26: Rudy::Huxtable.le "Connection Error. Check your internets!" 27: end 28: ip 29: end
Generates a canonical tag name in the form:
2009-12-31-USER-SUFFIX
where USER is equal to the user executing the Rudy process and SUFFIX is equal to suffix (optional)
# File lib/rudy/utils.rb, line 47 47: def generate_tag(suffix=nil) 48: n = DateTime.now 49: y, m = n.year.to_s.rjust(4, "20"), n.month.to_s.rjust(2, "0") 50: d, u = n.mday.to_s.rjust(2, "0"), Rudy.sysinfo.user 51: criteria = [y, m, d, u] 52: criteria << suffix unless suffix.nil? || suffix.empty? 53: criteria.join Rudy::DELIM 54: end
Returns the object type associated to str or nil if unknown.
- str is a string you’re investigating
# File lib/rudy/utils.rb, line 126 126: def id_type(str) 127: return false unless str 128: str &&= str.to_s.strip 129: (Rudy::ID_MAP.detect { |n,v| v == str.split('-').first } || []).first 130: end
Returns the string identifier associated to this key
# File lib/rudy/utils.rb, line 140 140: def identifier(key) 141: key &&= key.to_sym 142: return unless Rudy::ID_MAP.has_key?(key) 143: Rudy::ID_MAP[key] 144: end
Return the local IP address which receives external traffic from: coderrr.wordpress.com/2008/05/28/get-your-local-ip-address/ NOTE: This does not open a connection to the IP address.
# File lib/rudy/utils.rb, line 34 34: def internal_ip_address 35: # turn off reverse DNS resolution temporarily 36: orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true 37: ip = UDPSocket.open {|s| s.connect('75.101.137.7', 1); s.addr.last } # Solutious IP 38: ip 39: ensure 40: Socket.do_not_reverse_lookup = orig 41: end
Is the given string str an ID of type identifier?
- identifier is expected to be a key from ID_MAP
- str is a string you’re investigating
# File lib/rudy/utils.rb, line 117 117: def is_id?(identifier, str) 118: return false unless identifier && str && known_type?(identifier) 119: identifier &&= identifier.to_sym 120: str &&= str.to_s.strip 121: str.split('-').first == Rudy::ID_MAP[identifier].to_s 122: end
Is the given key a known type of object?
# File lib/rudy/utils.rb, line 133 133: def known_type?(key) 134: return false unless key 135: key &&= key.to_s.to_sym 136: Rudy::ID_MAP.has_key?(key) 137: end
Return a string ID without the identifier. e.g. key-stage-app-root => stage-app-root
# File lib/rudy/utils.rb, line 147 147: def noid(str) 148: el = str.split('-') 149: el.shift 150: el.join('-') 151: end
require a glob of files.
- path is a list of path elements which is sent to File.join
and then to Dir.glob. The list of files found are sent to require. Nothing is returned but LoadError exceptions are caught. The message is printed to STDERR and the program exits with 7.
# File lib/rudy/utils.rb, line 181 181: def require_glob(*path) 182: begin 183: # TODO: Use autoload 184: Dir.glob(File.join(*path.flatten)).each do |path| 185: require path 186: end 187: rescue LoadError => ex 188: puts "Error: #{ex.message}" 189: exit 7 190: end 191: end
Checks whether something is listening to a socket.
- host A hostname
- port The port to check
- wait The number of seconds to wait for before timing out.
Returns true if host allows a socket connection on port. Returns false if one of the following exceptions is raised: Errno::EAFNOSUPPORT, Errno::ECONNREFUSED, SocketError, Timeout::Error
# File lib/rudy/utils.rb, line 202 202: def service_available?(host, port, wait=3) 203: if Rudy.sysinfo.vm == :java 204: begin 205: iadd = Java::InetSocketAddress.new host, port 206: socket = Java::Socket.new 207: socket.connect iadd, wait * 1000 # milliseconds 208: success = !socket.isClosed && socket.isConnected 209: rescue NativeException => ex 210: puts ex.message, ex.backtrace if Rudy.debug? 211: false 212: end 213: else 214: begin 215: status = Timeout::timeout(wait) do 216: socket = Socket.new( AF_INET, SOCK_STREAM, 0 ) 217: sockaddr = Socket.pack_sockaddr_in( port, host ) 218: socket.connect( sockaddr ) 219: end 220: true 221: rescue Errno::EAFNOSUPPORT, Errno::ECONNREFUSED, SocketError, Timeout::Error => ex 222: puts ex.class, ex.message, ex.backtrace if Rudy.debug? 223: false 224: end 225: end 226: end
Generates a string of random alphanumeric characters.
- len is the length, an Integer. Default: 8
- safe in safe-mode, ambiguous characters are removed (default:
true):
i l o 1 0
# File lib/rudy/utils.rb, line 266 266: def strand( len=8, safe=true ) 267: chars = ("a".."z").to_a + ("0".."9").to_a 268: chars.delete_if { |v| %w(i l o 1 0).member?(v) } if safe 269: str = "" 270: 1.upto(len) { |i| str << chars[rand(chars.size-1)] } 271: str 272: end
Wait for something to happen.
- duration seconds to wait between tries (default: 2).
- max maximum time to wait (default: 240). Throws an exception when exceeded.
- logger IO object to print dot to.
- msg the message to print before executing the block.
- bells number of terminal bells to ring. Set to nil or false to keep the waiter silent
The check block must return false while waiting. Once it returns true the waiter will return true too.
# File lib/rudy/utils.rb, line 65 65: def waiter(duration=2, max=240, logger=STDOUT, msg=nil, bells=0, &check) 66: # TODO: Move to Drydock. [ed-why?] 67: raise "The waiter needs a block!" unless check 68: duration = 1 if duration < 1 69: max = duration*2 if max < duration 70: dot = '.' 71: begin 72: if msg && logger 73: logger.print msg 74: logger.flush 75: end 76: Timeout::timeout(max) do 77: while !check.call 78: sleep duration 79: logger.print dot if logger.respond_to?(:print) 80: logger.flush if logger.respond_to?(:flush) 81: end 82: end 83: rescue Timeout::Error => ex 84: retry if Annoy.pose_question(" Keep waiting?\a ", /yes|y|ya|sure|you bet!/i, logger) 85: return false 86: end 87: 88: if msg && logger 89: logger.puts 90: logger.flush 91: end 92: 93: Rudy::Utils.bell(bells, logger) 94: true 95: end
Returns str with the leading indentation removed. Stolen from github.com/mynyml/unindent/ because it was better.
# File lib/rudy/utils.rb, line 276 276: def without_indent(str) 277: indent = str.split($/).each {|line| !line.strip.empty? }.map {|line| line.index(/[^\s]/) }.compact.min 278: str.gsub(/^[[:blank:]]{#{indent}}/, '') 279: end
A basic file writer
# File lib/rudy/utils.rb, line 251 251: def write_to_file(filename, content, mode, chmod=600) 252: mode = (mode == :append) ? 'a' : 'w' 253: f = File.open(filename,mode) 254: f.puts content 255: f.close 256: return unless Rudy.sysinfo.os == :unix 257: raise "Provided chmod is not a Fixnum (#{chmod})" unless chmod.is_a?(Fixnum) 258: File.chmod(chmod, filename) 259: end