Scripting with RubyStuart PalmerRubyJax13 June 2013
6/13/2013Scripting with RubyWhy scripting? Perform regular tasks automatically Create daily reports, publish information...
6/13/2013Scripting with RubyTraditional Scripting Shell scripts sh, bash, csh, ksh DOS batch files .bat SQL Jobs SQL...
6/13/2013Scripting with RubySample shell script#!/bin/tcsh## Expects one parameter in mm/dd/yyyy format#setenv TOP /opt/sp...
6/13/2013Scripting with RubyWhat can Ruby do?Ruby Standard Library✔ Numbers and Math✔ Strings✔ Regular expressions✔ Collec...
6/13/2013Scripting with RubyMy First Exposure to Rubyrequire rubygemsrequire roorequire fileutilsss = Excel.new( "business...
6/13/2013Scripting with RubySending emailrequire net/smtp# Send emailNet::SMTP.start(mail.silveradosw.com, 25, www.silvera...
6/13/2013Scripting with RubyFile functions and FTPrequire filerequire fileutils# Write to a filereport_file = File.new(/tm...
6/13/2013Scripting with RubyFile functions and FTPrequire filerequire fileutilsrequire net/ftp# Write to a filereport_file...
6/13/2013Scripting with RubyClient / Serverrequire socketsocket = TCPSocket.open(localhost, 3333)socket.puts(hello)socket....
6/13/2013Scripting with RubyThreadingrequire threaddone        = falsesocket      = TCPServer.open(3333)connections = Queu...
6/13/2013Scripting with RubyDatabase Accessrequire daterequire rubygemsrequire dbi# Call database for datadbhandle = DBI.c...
6/13/2013Scripting with RubyOther Useful Modules● Log filesrequire loggerlog = Logger.new(STDOUT)log.level = Logger::WARNl...
6/13/2013Scripting with RubyGems● XML Generation✔ nokogiri● PDF Generation✔ prawn● Events / Timers✔ eventmachine
6/13/2013Scripting with RubyTest First● The usual test frameworks can be used➢ rspec, test::unit, minitestC:UsersStuartCli...
6/13/2013Scripting with Rubyexit(0)Stuart PalmerSilverado Consulting, Inc.stuart@silveradosw.com(408)529-6891
Upcoming SlideShare
Loading in …5
×

Ruby Scripting

445 views
310 views

Published on

Writing background and automated programs using Ruby.
Presentation for RubyJax Meetup 6/13/2013

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
445
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Ruby Scripting

  1. 1. Scripting with RubyStuart PalmerRubyJax13 June 2013
  2. 2. 6/13/2013Scripting with RubyWhy scripting? Perform regular tasks automatically Create daily reports, publish information, back up files, clear history Perform background tasks Send emails, share information with other systems Easily use operating system programs/utilities FTP, scp, mail, file storage
  3. 3. 6/13/2013Scripting with RubyTraditional Scripting Shell scripts sh, bash, csh, ksh DOS batch files .bat SQL Jobs SQL scripts in database
  4. 4. 6/13/2013Scripting with RubySample shell script#!/bin/tcsh## Expects one parameter in mm/dd/yyyy format#setenv TOP /opt/spsetenv SBIN ${TOP}/sbinsetenv LOG ${TOP}/logset logDir=${LOG}/trade­totals## Convert mm/dd/yyyy to yyyymmdd#set yyyy=`echo $1 | cut ­c7­10`set mm=`echo $1 | cut ­c1­2`set dd=`echo $1 | cut ­c4­5`set tradeDate=${yyyy}${mm}${dd}set saveDir=${logDir}/${yyyy}## Run the totals#fisql ­Uxxx ­Pxxx ­Ssss ­w140 > /tmp/total.out <<EOFexec getTotals $1goquitEOF## See if there was any output#if ( ­z /tmp/total.out ) then   rm ­f /tmp/total.out   exit 0endif## Nice formatting#echo "" > /tmp/total.faxecho "Totals for $1" >> /tmp/total.faxecho "" >> /tmp/total.fax## Get rid of isql junk#cat /tmp/total.out | grep ­v line1 | grep ­v ­­­ | grep ­v   "return stat" | egrep ­v ­e ^$ > /tmp/total.out1## Get rid of tabs#sed ­e "s///" /tmp/total.out1 >> /tmp/total.faxrm ­f /tmp/total.out /tmp/total.out1## Send the file to the mail server for emailing#${SBIN}/email­to­finop.csh "Trade Totals for $1" /tmp/total.fax## Save the file for prosperity#if ( ! ­d ${saveDir} ) then    mkdir ${saveDir}endifmv ­f /tmp/total.fax ${saveDir}/total.${tradeDate}
  5. 5. 6/13/2013Scripting with RubyWhat can Ruby do?Ruby Standard Library✔ Numbers and Math✔ Strings✔ Regular expressions✔ Collections✔ Dates and Times✔ Files and Directories✔ Networking✔ Threads
  6. 6. 6/13/2013Scripting with RubyMy First Exposure to Rubyrequire rubygemsrequire roorequire fileutilsss = Excel.new( "business_plan_cmbs.xls" )ss.default_sheet = "Recommended"puts ss.cell(B, 8)C.upto(BJ) do |column|  date      = ss.cell(2, column)  monthnum  = ss.cell(3, column)  yearnum   = ss.cell(4, column)    interest  = ss.cell(8, column)  amort     = ss.cell(9, column)  other     = ss.cell(10, column)  sum       = interest + amort + other  puts "#{date} (#{monthnum}/#{yearnum})t#{sum}" end
  7. 7. 6/13/2013Scripting with RubySending emailrequire net/smtp# Send emailNet::SMTP.start(mail.silveradosw.com, 25, www.silveradosw.com) do |smtp|  smtp.open_message_stream(stuart@silveradosw.com, rubyjax@meetup.com) do |f|    f.puts From: Stuart Palmer <stuart@silveradosw.com>    f.puts To: Ruby Jax <rubyjax@meetup.com>    f.puts "Date: #{DateTime.now.rfc2822}"    f.puts Subject: Your Report for today    f.puts Message­ID: <ruby­1234@silveradosw.com>    lines.each do |line|      f.puts line    end  endend
  8. 8. 6/13/2013Scripting with RubyFile functions and FTPrequire filerequire fileutils# Write to a filereport_file = File.new(/tmp/report­new, w)lines.each do |line|  report_file.puts lineendreport_file.closeFileUtils.mv(/tmp/report­new, /opt/xxx/todays­report)# FTP the fileftp = Net::FTP.new(ftp.silveradosw.com)ftp.login(stuart@silveradosw.com, xxx)ftp.passive = trueftp.chdir(Reports)ftp.puttextfile(/tmp/report­new, todays_report)ftp.close
  9. 9. 6/13/2013Scripting with RubyFile functions and FTPrequire filerequire fileutilsrequire net/ftp# Write to a filereport_file = File.new(/tmp/report­new, w)lines.each do |line|  report_file.puts lineendreport_file.closeFileUtils.mv(/tmp/report­new, /opt/xxx/todays­report)# FTP the fileftp = Net::FTP.new(ftp.silveradosw.com)ftp.login(stuart@silveradosw.com, xxx)ftp.passive = trueftp.chdir(Reports)ftp.puttextfile(/tmp/report­new, todays_report)ftp.close
  10. 10. 6/13/2013Scripting with RubyClient / Serverrequire socketsocket = TCPSocket.open(localhost, 3333)socket.puts(hello)socket.puts(what?)socket.puts(done)socket = TCPSocket.open(localhost, 3333)socket.puts(quit)require socketsocket = TCPSocket.new(localhost, 3333)done_listening = falsewhile !done_listening  done_reading = false  while !done_reading    message = socket.read    if message =~ /^quit$|^stop$/i      puts "Received shutdown message."      done_listening = true      done_reading = true    elsif message =~ /^done$/i      puts "Received client end message."      done_reading = true    else      puts "Read message: [#{message}]"      socket.puts "OKn"    end  end  socket.closeend
  11. 11. 6/13/2013Scripting with RubyThreadingrequire threaddone        = falsesocket      = TCPServer.open(3333)connections = Queue.newprocessor   = Thread.new { process(connections, cfg) }while !done  # Block, waiting for a request  client, client_sock_adr = socket.accept  port, host, ipno = client.peeraddr[1..3]  # Process the request  begin    message = client.readline  rescue => ex    client.close    next  end  # Pass off the message and go wait for another one  connections << OpenStruct.new(client: client, msg: message)endprocessor.joinsocket.closedef process(connections, cfg)  while !connections.empty?    connection = connections.pop    client = connection.get_client    port, host, ipno = client.peeraddr[1..3]    # Do stuff  endend
  12. 12. 6/13/2013Scripting with RubyDatabase Accessrequire daterequire rubygemsrequire dbi# Call database for datadbhandle = DBI.connect("dbi:#{sss}", xxx, xxx)rows = dbhandle.select_all("EXEC getTotals ?", ARGV[0])if rows.nil? or rows.empty?  puts "Nothing to report"  exitendlines  = []lines << "Your report for #{Date.today.to_s}"lines << rows.each do |row|  lines << row[column_name]end
  13. 13. 6/13/2013Scripting with RubyOther Useful Modules● Log filesrequire loggerlog = Logger.new(STDOUT)log.level = Logger::WARNlog.debug( Created logger )log.info( Program started )log.warn( Nothing to do! )● Configuration filesconfig = File.open( report.yaml ) { |yf| YAML::load( yf ) }config = JSON.parse( IO.read( report.json ) )
  14. 14. 6/13/2013Scripting with RubyGems● XML Generation✔ nokogiri● PDF Generation✔ prawn● Events / Timers✔ eventmachine
  15. 15. 6/13/2013Scripting with RubyTest First● The usual test frameworks can be used➢ rspec, test::unit, minitestC:UsersStuartClientswhbbiwhbbireports> rspec ­c ­fs trade­totals­email­spec.rbTradeTotalsEmail  initialize    should call BaseEmail::new    should call BaseEmail#from with name and email when set in config  set_sender    should call BaseEmail#from with name and email  set_recipients    should call add_recipients with passed­in name/email array    should call add_recipients with config name/email  set_default_recipients    should call add_to with config name and email  add_recipients    should call add_to with each passed­in name and email  add_to    should call BaseEmail:to when non­null name and email passed inFinished in 0.018 seconds8 examples, 0 failures
  16. 16. 6/13/2013Scripting with Rubyexit(0)Stuart PalmerSilverado Consulting, Inc.stuart@silveradosw.com(408)529-6891

×