Chandrashekar Babu's blog
My company website is largely functional now
Finally, I managed to put together all pending efforts to get my company website up and working. Well - its in a perpetual beta mode right now. A lot of work is still pending. But it must be largely usable right now (with some rough edges - of course).
As an update, I will be conducting full-time (8 hours stretch) fast track training programs on a couple of technologies starting this month. More information about it can be found at http://www.slashprog.com/
Be sure to tune into http://www.slashprog.com/events.html to get the latest updates on training programs that I conduct at my office premises.
God bless!
Ruby sample scripts - Active records
add-cities.rb
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:database => "rails_learn",
:user => "root",
:password => "welcome"
)
class City < ActiveRecord::Base ; end
City.create(:name => "Chennai", :country => "India")
City.create(:name => "Sydney", :country => "Australia")
add-people.rb
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:database => "rails_learn",
:user => "root",
:password => "welcome"
)
class Person < ActiveRecord::Base
belongs_to :city
has_and_belongs_to_many :book
end
class Book < ActiveRecord::Base
has_and_belongs_to_many :person
end
class City < ActiveRecord::Base
has_many :person
end
Person.create(:name => "John", :city =>
City.find(:first, :conditions =>
{ :name => "Sydney" }))
Book.create(:name => "Programming in Ruby", :isbn => "343434")
create-books.rb
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:database => "rails_learn",
:user => "root",
:password => "welcome"
)
ActiveRecord::Base.connection.create_table :books do |t|
t.column :name, :string, :length=>32
t.column :isbn, :string, :length=>10
end
create-person.rb
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:database => "rails_learn",
:user => "root",
:password => "welcome"
)
ActiveRecord::Base.connection.create_table :city do |t|
t.column :name, :string, :length=>32
t.column :country, :string
end
ActiveRecord::Base.connection.create_table :people do |t|
t.column :name, :string, :length => 32
t.references :city
end
entries.rb
require 'ActiveRecord'
class Entries < ActiveRecord::Base
end
entry = Entry.new
entry.name = "John"
entry.comments = "What a great Web site!"
entry.save
entry = Entry.find(1)
puts entry.name # output: "John"
find-cities.rb
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:database => "rails_learn",
:user => "root",
:password => "welcome"
)
class City < ActiveRecord::Base ; end
my_city = City.find(:first, :conditions => {:name => "Chennai" })
print my_city.name
print my_city.country
people-books.rb
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:database => "rails_learn",
:user => "devel",
:password => "welcome"
)
class Person < ActiveRecord::Base
belongs_to :city
end
class City < ActiveRecord::Base
has_many :person
end
Person.create(:name => "John", :city =>
City.find(:first, :conditions =>
{ :name => "Sydney" }))
simple.rb
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:database => "rails_learn",
:user => "devel",
:password => "welcome"
)
class Rubyist < ActiveRecord::Base
end
Rubyist.create(:name => 'Luc Juggery', :city => "Nashville, Tenessee")
Rubyist.create(:name => 'Sunil Kelkar', :city => "Pune, India")
Rubyist.create(:name => 'Adam Smith', :city => "San Fransisco, USA")
participant = Rubyist.find(:first)
puts %{#{participant.name} stays in #{participant.city}}
#Rubyist.find(:first).destroy
Ruby sample scripts - Looping constructs
loop1.rb
#!/usr/bin/env ruby
for x in 1..10
puts "Counting " + x.to_s
end
loop2.rb
#!/usr/bin/env ruby
for x in 1...10
puts "Counting " + x.to_s
end
loop3.rb
#!/usr/bin/env ruby
10.times do |i|
puts "Counting #{i}"
end
loop4.rb
#!/usr/bin/env ruby
(1..10).each {|i| puts "Counting #{i}" }
loop5.rb
#!/usr/bin/env ruby
1.upto(10) {|i| puts "Counting #{i}" }
loop6.rb
#!/usr/bin/env ruby
# Checking whether a number is prime can be
# much simpler than this. But this example demonstrates
# loop construct and duck-typing.
# A simple duck-typing example.
# Add a new method/functionality to an existing class
class Fixnum
def is_prime?
(2..Math.sqrt(self).floor).each {|x| return false if self % x == 0 }
return true
end
end
loop do
print "Enter a number (0 to exit): "
num = gets.to_i
break if num == 0
puts "#{num} is" + (num.is_prime? ? " " : " NOT ") + "prime."
end
loop7.rb
puts "Ho! Ho! Ho!" while (Time.now.min == 15)
#while (Time.now.min == 15)
# puts "Ho! Ho! Ho!"
#end
num1.rb
#!/usr/bin/env ruby
10.times do
puts "Hello"
end
num2.rb
#!/usr/bin/env ruby
10.times do |x|
puts "Counting " + x.to_s
end
Ruby sample scripts - file operations
calc-dir-size.rb
#!/usr/bin/env ruby
size = 0
Dir.open(ARGV[0]).each { |file| size += File.size? ARGV[0] + "/" + file }
puts size
calc-dir-size.sh
#!/bin/bash
SIZE=0
DIR=$1
for file in $DIR/*
do
((SIZE+=$(stat -c "%s" "$file")))
done
echo $SIZE
calc-dir-size2.rb
#!/usr/bin/env ruby
# Run as below:
# ls -l /bin | ruby calc-dir-size2.rb
total = 0
STDIN.read.each {|line| total += line.split(" ")[4].to_i }
puts total
calc-dir-size2.sh
#!/bin/sh
DIR=$1
expr $(ls -l $DIR | sed 's/ \+/ /g' | cut -f5 -d' ' | xargs | sed 's/ / + /g')
calc-dir-size3.sh
#!/bin/sh
DIR=$1
ls -l $DIR | awk '{ total += $5 } END { print total }'
check-file.rb
#!/usr/bin/env ruby
if ARGV.length < 1
puts "Enter filename/path: "
file = gets
else
file = ARGV[0]
end
# Generic redundant code below. Commented.
#puts "File #{file} exists." if File.exist? file
#puts "File #{file} is a regular file." if File.file? file
#puts "File #{file} is a directory." if File.directory? file
#puts "File #{file} is a symlink." if File.symlink? file
#puts "File #{file} is a block device file." if File.blockdev? file
#puts "File #{file} is a character device file." if File.chardev? file
#puts "File #{file} is a socket file." if File.socket? file
#puts "File #{file} is a FIFO file." if File.pipe? file
#puts "-" * 40
#puts "File #{file} is readable." if File.readable? file
#puts "File #{file} is writable." if File.writable? file
#puts "File #{file} is executable/searchable." if File.executable? file
#puts "File #{file} has SETUID-bit set." if File.setuid? file
#puts "File #{file} has SETGID-bit set." if File.setgid? file
#puts "File #{file} has sticky-bit set." if File.sticky? file
#puts "File #{file} is owned by current effective user." if File.owned? file
#puts "File #{file} is owned by current effective group." if File.grpowned? file
#puts "File #{file} is empty." if File.zero? file
# Smarter code below.
file_methods = {
:exist? => "exists",
:file? => "is a regular file",
:directory? => "is a directory",
:symlink? => "is a symbolic link",
:blockdev? => "is a block device file",
:chardev? => "is a character device file",
:pipe? => "is a FIFO file",
:socket? => "is a UNIX socket file",
:readable? => "is readable",
:writable? => "is writable",
:executable? => "is executable/searchable",
:setuid? => "has set-UID bit set",
:setgid? => "has set-GID bit set",
:sticky? => "has sticky bit set",
:owned? => "is owned by current effective user",
:grpowned? => "is owned by current effective group",
:zero? => "is an empty file"
}
file_methods.each {|method, message| puts "File #{file} #{message}" if File.send method, file }
chmod.rb
#!/usr/bin/env ruby
File.chmod 0644, "test.txt"
cp.rb
#!/usr/bin/env ruby
# Validations... validations... validations...
if ARGV.length < 2
STDERR.write "usage: #{$0} source-file destination-file.\n"
exit 1
end
unless File.file? ARGV[0]
STDERR.write "#{$0}: #{ARGV[0]}: not a regular file.\n"
exit 2
end
if File.exists? ARGV[1]
print "Destination #{ARGV[1]} already exists. Overwrite (y/n) ? "
exit 3 unless gets.upcase.start_with? "Y"
end
# Phew, this is where the actual work gets done.
# The commented code below is the pythonic way of doing it.
# File.open(ARGV[0]) do |src|
# File.open(ARGV[1], "w") do |dst|
# dst.write src.read
# end
# end
# The code below is the Rubyist way of doing it ;-)
puts "Copied #{File.open(ARGV[1], "w").write(File.open(ARGV[0]).read)} bytes from #{ARGV[0]} to #{ARGV[1]}"
delete-file.rb
#!/usr/bin/env ruby
if ARGV.length < 1
print "Enter file to delete: "
file = gets.chomp!
else
file = ARGV[0]
end
File.delete file
listdir.rb
d = Dir.new(ARGV[0])
d.each {|file| puts file }
recursive-copy.rb
#!/usr/bin/env ruby
require 'Fileutils'
if ARGV.length < 2
STDERR.write "usage: #{$0} source-file destination-file.\n"
exit 1
end
unless File.file? ARGV[0]
STDERR.write "#{$0}: #{ARGV[0]}: not a regular file.\n"
exit 2
end
if File.exists? ARGV[1]
print "Destination #{ARGV[1]} already exists. Overwrite (y/n) ? "
exit 3 unless gets.upcase.start_with? "Y"
end
Fileutils.cp_r ARGV[0], ARGV[1]
rename-file.rb
#!/usr/bin/env ruby
if ARGV.length < 2
STDERR.write "usage: #{$0} source-file destination-file.\n"
exit 1
end
unless File.file? ARGV[0]
STDERR.write "#{$0}: #{ARGV[0]}: not a regular file.\n"
exit 2
end
if File.exists? ARGV[1]
print "Destination #{ARGV[1]} already exists. Overwrite (y/n) ? "
exit 3 unless gets.upcase.start_with? "Y"
end
File.rename ARGV[0], ARGV[1]
scan-setuid-files.rb
#!/usr/bin/env ruby
Dir.open(ARGV[0]).each { |file| puts file if File.setuid? ARGV[0] + "/" + file }
Ruby sample scripts - sockets (examples from Ruby manual)
clnt.rb
# socket example - client side
# usage: ruby clnt.rb [host] port
require "socket"
if ARGV.length >= 2
host = ARGV.shift
else
host = "localhost"
end
print("Trying ", host, " ...")
STDOUT.flush
s = TCPSocket.open(host, ARGV.shift)
print(" done\n")
print("addr: ", s.addr.join(":"), "\n")
print("peer: ", s.peeraddr.join(":"), "\n")
while line = gets()
s.write(line)
print(s.readline)
end
s.close
svr.rb
# socket example - server side
# usage: ruby svr.rb
# this server might be blocked by an ill-behaved client.
# see tsvr.rb which is safe from client blocking.
require "socket"
gs = TCPserver.open(0)
addr = gs.addr
addr.shift
printf("server is on %s\n", addr.join(":"))
socks = [gs]
loop do
nsock = select(socks);
next if nsock == nil
for s in nsock[0]
if s == gs
ns = s.accept
socks.push(ns)
print(s, " is accepted\n")
else
if s.eof?
print(s, " is gone\n")
s.close
socks.delete(s)
# single thread gets may block whole service
elsif str = s.gets
s.write(str)
end
end
end
end
tsvr.rb
# socket example - server side using thread
# usage: ruby tsvr.rb
require "socket"
gs = TCPserver.open(0)
addr = gs.addr
addr.shift
printf("server is on %s\n", addr.join(":"))
loop do
Thread.start(gs.accept) do |s|
print(s, " is accepted\n")
while line = s.gets
s.write(line)
end
print(s, " is gone\n")
s.close
end
end
Ruby sample scripts - Threads
observ.rb
#! /usr/local/bin/ruby
require "thread"
require "observer"
class Tick
include Observable
def initialize
Thread.start do
loop do
sleep 0.999
now = Time.now
changed
notify_observers(now.hour, now.min, now.sec)
end
end
end
end
class Clock
def initialize(tick)
@tick = tick
@tick.add_observer(self)
end
def update(h, m, s)
printf "\e[8D%02d:%02d:%02d", h, m, s
STDOUT.flush
end
end
clock = Clock.new(Tick.new)
sleep
philos.rb
#
# The Dining Philosophers - thread example
#
require "thread"
srand
#srand
N=9 # number of philosophers
$forks = []
for i in 0..N-1
$forks[i] = Mutex.new
end
$state = "-o"*N
def wait
sleep rand(20)/10.0
end
def think(n)
wait
end
def eat(n)
wait
end
def philosopher(n)
while true
think n
$forks[n].lock
if not $forks[(n+1)%N].try_lock
$forks[n].unlock # avoid deadlock
next
end
$state[n*2] = ?|;
$state[(n+1)%N*2] = ?|;
$state[n*2+1] = ?*;
print $state, "\n"
eat(n)
$state[n*2] = ?-;
$state[(n+1)%N*2] = ?-;
$state[n*2+1] = ?o;
print $state, "\n"
$forks[n].unlock
$forks[(n+1)%N].unlock
end
end
for n in 0..N-1
Thread.start(n){|i| philosopher(i)}
sleep 0.1
end
sleep
producer-consumer.rb
require 'thread'
queue = Queue.new
producer = Thread.new do
5.times do |i|
sleep rand(i) # simulate expense
queue << i
puts "#{i} produced"
end
end
consumer = Thread.new do
5.times do |i|
value = queue.pop
sleep rand(i/2) # simulate expense
puts "consumed #{value}"
end
end
gets
Ruby sample scripts - Object Orientation
CloneTest.rb
# A Bad example for implementing accessors.
# Very much Java-like. See CloneTest2.rb
# for better implementation
class Address
def setCity(city)
@city = city
end
def getCity
@city
end
end
class Person
def getName
@name
end
def setName(name)
@name = name
end
def getAge
@age
end
def setAge(age)
@age = age
end
def getLocation
@location
end
def setLocation(loc)
@location = loc
end
end
p1 = Person.new
p1.setLocation Address.new
p1.setName "John"
p1.setAge 12
p1.getLocation.setCity "Chennai"
p2 = p1.clone # Shallow copy!
p1.setName "Smith"
p1.setAge 16
p1.getLocation.setCity "Delhi"
puts "Person p1 -> name: #{p1.getName}, age: #{p1.getAge}, city: #{p1.getLocation.getCity}"
puts "Person p2 -> name: #{p2.getName}, age: #{p2.getAge}, city: #{p2.getLocation.getCity}"
CloneTest2.rb
class Address
attr_accessor :city
end
class Person
attr_accessor :name, :age, :location
end
p1 = Person.new
p1.location = Address.new
p1.name = "John"
p1.age = 12
p1.location.city = "Chennai"
p2 = p1.clone # Shallow copy!
p2.name = "Bourne"
p2.age = 16
p2.location.city = "Delhi"
puts "Person p1 -> name: #{p1.name}, age: #{p1.age}, city: #{p1.location.city}"
puts "Person p2 -> name: #{p2.name}, age: #{p2.age}, city: #{p2.location.city}"
exception-test.rb
def printCallTrace
calltrace = caller
calltrace.each {|line| puts line }
end
class MyObject
def greet
puts "Hello..."
printCallTrace
end
end
begin
obj = MyObject.new
obj.greet
f = File.open("test.txt")
f.each_line do |line|
puts line
end
f.close
obj.sayHello
rescue SystemCallError
puts "Error in System call:" + $!
rescue NoMethodError
puts "Method not found: " + $!
return false
ensure
f.close unless f.nil?
end
puts "End of program..."
laptop.rb
require "openclose"
# Demonstration of module (cross-cutting functionality)
class Laptop
include OpenClose
def initialize
puts "Laptop initialized..."
end
end
class Cupboard
include OpenClose
def initialize
puts "Cupboard instantiated..."
end
end
laptop = Laptop.new
laptop.open
laptop.close
cupboard = Cupboard.new
cupboard.open
cupboard.close
method_missing_example.rb
class Foo
def method_missing(method_name, *args)
print "Method: #{method_name} called\n"
end
def sayHello(args)
puts "Hello #{args}"
end
end
foo = Foo.new
foo.sayHello("John")
foo.greet
foo.sdfsddsf
MyString.rb
class String
def speak
puts "My own custom method..."
end
end
str = "Hello world..."
str.speak
openclose.rb
module OpenClose
def open
puts "opened..."
end
def close
puts "closed..."
end
end
Person.rb
class Person
attr_reader :name, :age, :city
attr_writer :name, :age, :city
def greet
@name = "John"
puts "Hello..."
end
def sayGoodBye
puts @name
puts "Good bye..."
end
# private :sayGoodBye
end
#p = Person.new
#p.greet if p.respond_to?(:sdfsdfsd)
#p.sayGoodBye
#p.name = "Smith"
#puts p.name
#print "Enter method: "
#method_name = gets.chomp
#p = Person.new
#p.send(method_name);
SingletonTest.rb
require 'singleton'
class World
include Singleton
def show_id
self.object_id
end
end
a = World.instance
b = World.instance
puts a.show_id
puts b.show_id
Ruby sample scripts - advanced (miscellaneous)
escape-elements.rb
require 'cgi'
str = "<html><h1>This is 'a' <i>test</i> string</h1></html>"
puts str
puts CGI.escapeElement(str, "h1", "html")
puts CGI.escapeHTML(str)
input-timeout.rb
require 'thread'
puts "Enter your name: "
catch (:timeout) do
timeout_thread = Thread.new do
5.times do
sleep 1
print "."
STDOUT.flush
end
puts "-- TIMEOUT --"
exit -1
throw :timeout
end
name = gets
puts "Hello " + name
end
marshal-retrieve.rb
require 'Person'
File.open("marshalled.bin") do |data|
p = Marshal.load(data)
puts p.name
end
marshal-test.rb
require 'Person'
p = Person.new
p.name = "Smith"
p.age = 15
p.city = "Bengaluru"
p2 = Person.new
p2.name = "Sam"
p2.age = 10
p2.city = "Chennai"
file = File.new("marshalled.bin", "w")
data = Marshal.dump(p)
file.puts(data)
data = Marshal.dump(p2)
file.puts(data)
file.close
pstore-retrieve.rb
require 'Person'
require 'pstore'
store = PStore.new("object.bin")
store.transaction do
p = store['1']
p2 = store["aaa"]
puts "Person 1: name -> #{p.name}, age -> #{p.age}"
puts "Person 2: name -> #{p2.name}, age -> #{p2.age}"
end
pstore-test.rb
require 'Person'
require 'pstore'
p = Person.new
p.name = "Smith"
p.age = 15
p.city = "Bengaluru"
p2 = Person.new
p2.name = "Sam"
p2.age = 10
p2.city = "Chennai"
store = PStore.new("object.bin")
store.transaction do
store['1'] = p
store['aaa'] = p2
end
test-mymodule.rb
require 'MyModules/Test'
MyModules::Test.foo
url-escape.rb
require 'cgi'
url = "http://www.chandrashekar.info/q=' sfdgdsfg &%# @' "
puts url
new_url = CGI.escape(url)
puts new_url
user-agent-test.rb
require 'net/http'
request = Net::HTTP.new("www.chandrashekar.info", 80)
response, data = request.get("/contact", nil)
#response.each {|line| puts line }
puts data
Ruby sample scripts - simple
boolean_methods.rb
#!/usr/bin/env ruby
# Print all methods that end with a ?.
puts File.methods.select {|m| m =~ /\?$/ }.join "\n"
catch-test.rb
catch(:done) do
while (true) do
line = gets
if line.chomp == 'exit'
throw :done
end
puts line.upcase
end
end
puts "exiting catch block..."
check-name.rb
name = gets
if name =~ /^J/
puts "Hello J!"
else
puts "Good morning..."
end
unless name == nil
name.gsub!(/a/, "b");
end
puts name
count10.rb
#!/usr/bin/env ruby
def count10
(1..10).each {
yield
}
end
count10 do
puts "Hello"
end
freeze-test.rb
name = "John"
puts name
name.freeze
name << " Smith" unless name.frozen?
puts name
a = name.clone
a << " Kerry"
puts a
greetjohn.rb
puts "Welcome home,john!" if ARGV[0] == "john"
#if ARGV[0] == "john"
# puts "Welcome home, john!"
#end
hello.rb
#!/usr/bin/env ruby
puts "Hello, Ruby!"
print "Hello, Ruby!\n"
STDOUT.write "Hello, Ruby!\n"
method_alias.rb
def foo
puts "This is foo method..."
end
foo
alias bar foo
bar
method_param.rb
#!/usr/bin/env ruby
#def foo
# puts "no params..."
#end
#
#def foo1(x)
# puts "method with param " + x
#end
#
#def foo2(*x)
# puts "method with variable args..."
# x.each {|a| puts a }
#end
#
#def get_user_info
# ["john", "welcome", 101]
#end
#
def add_user(args, admin=True)
name = defined? args[:name] ? args[:name] : "Anonymous"
age = defined? args[:age] ? args[:age] : 12
# role = args.has_key?(:admin) ? "admin" : "user"
role = :admin ? "admin" : "user"
puts "name: #{name}, age: #{age}, role: #{role}"
end
add_user :name => "John", :age => 13
add_user
add_user :name => "Smith"
add_user :age => 15
#add_user :name => "Adrian", :admin => True, :age => 25
#foo
#foo1 "hello"
#foo2("aaa", 30, 3.4)
#username, password, uid = get_user_info
#puts "username: #{username}, password: #{password}, uid: #{uid}"
regex-test.rb
#!/usr/bin/env ruby
print "Enter username: "
uname = gets.chomp
case uname
when /^J/
puts "Welcome J!"
when /^[aeiou]/
puts "Name starting with a vowel"
when /\d/
puts "Found digit in a name"
else
puts "Welcome #{uname}, pleased to meet you..."
end
simple-raise.rb
def foo(x)
if x != 'smith'
raise
end
end
begin
puts "Starting foo method"
foo('john')
puts "Finished method - foo"
rescue
puts "Caught an exception..."
end
SumOf.rb
def sumOf(*numbers)
sum = 0
numbers.each do |num|
sum += num
end
return sum
end
print sumOf(10, 20, 30, 40, 50)
table.rb
#!/usr/bin/env ruby
if ARGV.length < 1
print "Enter a number: "
num = gets.to_i
else
num = ARGV[0].to_i
end
(1..10).each {|count| puts "#{num} x #{count} = #{num*count}" }
table1.rb
#!/usr/bin/env ruby
if ARGV.length < 1
puts "usage: #{$0} number."
exit -1
end
num = ARGV[0].to_i
1.upto(10) do |count|
# puts "#{num} x #{count} = #{num * count}"
puts "%3d x %2d = %4d" % [num, count, num*count]
end
(1..10).each do |count|
puts "%3d x %2d = %4d" % [num, count, num*count]
end
taint-test.rb
a = "Test string..."
a.taint
puts a
a << "new value" unless a.tainted?
puts a
test-equal.rb
a = "John"
b = "John"
c = a
puts "a -> b: Same..." if a.equal? b
puts "c -> a: Same..." if c.equal? a
puts "c -> b: Same..." if c.equal? b
to_methods.rb
#!/usr/bin/env ruby
# Print all methods starting with to_* from a class.
puts File.methods.select {|m| m.start_with? "to_" }.join "\n"
yield-test.rb
#!/usr/bin/env ruby
def foo
yield
yield
end
foo do
puts "Hello"
end
yield2.rb
#!/usr/bin/env ruby
def count10
yield "Hello"
yield 10
yield "Test String"
yield "Hi"
end
count10 do |x|
puts x
end