Introduction#
Ruby for Admins is designed to be a source of information and inspiration for all Sysadmins, DBAs, Application Administrators, who are tired and bored scripting with XX century, ancient languages, tools and shells, and who want to learn to use modern programming languages and techniques. If you already know Ruby, you might find here an inspiration for using it in your daily work. If you don’t know it yet, you’ll be able to learn the basics here - but only the basics, do not expect full Ruby course.
To give you an idea how quick and easy is to work with Ruby, let’s take a look at almost-real-world example. Assume you want to develop a shell script, which creates a series of SQLs to kill all the active Oracle sessions. In the Shell, you might write it like this:
#!/bin/bash
sids_and_serials=`sqlplus -L -S $1/$2@$3 << EOF
set feed off
set head off
set pages 0
set line 1300
set termout off
select sid || ',' || serial# from v\\$session where status='ACTIVE';
exit
EOF`
ret_code=$?
if [ "$ret_code" -ne 0 ]; then
echo "Can't connect to the database!"
else
for s in $sids_and_serials; do
echo "alter system kill session '$s';";
done
fi
In Ruby, the same script would look like this:
#!/usr/bin/env ruby
require 'oci8'
dbconnection = OCI8.new(ARGV[0], ARGV[1], dbname=ARGV[2])
dbconnection.exec("select sid, serial# from v$session where status='ACTIVE'") do |row|
puts "alter system kill session '#{row[0].to_i}, #{row[1].to_i}';"
end
First at all, there is no need to run sqlplus anymore - thanks to oci8 gem (gems are Ruby libraries and oci8 is the one for Oracle connectivity) loaded in the second line with require
command. In the Shell Script, you should check the return code and break the script if sqlplus fails, to ensure the script will not continue. In Ruby, there is no need to do it: in case when OCI8.new()
cannot connect to the database generates an exception and break the program flow. As you probably guess, ARGV
is the array with command line arguments, puts
is an equivalent of echo in shell, and #{}
is used for string formatting. But where is the for loop? Well, we will try to solve this mystery!
This book is written by Tomasz ‘Grych’ Gryszkiewicz. Do not hestitate to contact me at grych@tg.pl or check my page.
©2014 - 2024 Tomasz Gryszkiewicz. All rights reserved.