SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Scripting with Ruby
Stuart Palmer
RubyJax
13 June 2013
6/13/2013Scripting with Ruby
Why 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
6/13/2013Scripting with Ruby
Traditional Scripting
 Shell scripts
 sh, bash, csh, ksh
 DOS batch files
 .bat
 SQL Jobs
 SQL scripts in database
6/13/2013Scripting with Ruby
Sample shell script
#!/bin/tcsh
#
# Expects one parameter in mm/dd/yyyy format
#
setenv TOP /opt/sp
setenv SBIN ${TOP}/sbin
setenv LOG ${TOP}/log
set 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 <<EOF
exec getTotals '$1'
go
quit
EOF
#
# See if there was any output
#
if ( ­z /tmp/total.out ) then
   rm ­f /tmp/total.out
   exit 0
endif
#
# Nice formatting
#
echo "" > /tmp/total.fax
echo "Totals for $1" >> /tmp/total.fax
echo "" >> /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.fax
rm ­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}
endif
mv ­f /tmp/total.fax ${saveDir}/total.${tradeDate}
6/13/2013Scripting with Ruby
What can Ruby do?
Ruby Standard Library
✔ Numbers and Math
✔ Strings
✔ Regular expressions
✔ Collections
✔ Dates and Times
✔ Files and Directories
✔ Networking
✔ Threads
6/13/2013Scripting with Ruby
My First Exposure to Ruby
require 'rubygems'
require 'roo'
require 'fileutils'
ss = 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
6/13/2013Scripting with Ruby
Sending email
require 'net/smtp'
# Send email
Net::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
  end
end
6/13/2013Scripting with Ruby
File functions and FTP
require 'file'
require 'fileutils'
# Write to a file
report_file = File.new('/tmp/report­new', 'w')
lines.each do |line|
  report_file.puts line
end
report_file.close
FileUtils.mv('/tmp/report­new', '/opt/xxx/todays­report')
# FTP the file
ftp = Net::FTP.new('ftp.silveradosw.com')
ftp.login('stuart@silveradosw.com', 'xxx')
ftp.passive = true
ftp.chdir('Reports')
ftp.puttextfile('/tmp/report­new', 'todays_report')
ftp.close
6/13/2013Scripting with Ruby
File functions and FTP
require 'file'
require 'fileutils'
require 'net/ftp'
# Write to a file
report_file = File.new('/tmp/report­new', 'w')
lines.each do |line|
  report_file.puts line
end
report_file.close
FileUtils.mv('/tmp/report­new', '/opt/xxx/todays­report')
# FTP the file
ftp = Net::FTP.new('ftp.silveradosw.com')
ftp.login('stuart@silveradosw.com', 'xxx')
ftp.passive = true
ftp.chdir('Reports')
ftp.puttextfile('/tmp/report­new', 'todays_report')
ftp.close
6/13/2013Scripting with Ruby
Client / Server
require 'socket'
socket = TCPSocket.open('localhost', 3333)
socket.puts('hello')
socket.puts('what?')
socket.puts('done')
socket = TCPSocket.open('localhost', 3333)
socket.puts('quit')
require 'socket'
socket = TCPSocket.new('localhost', 3333)
done_listening = false
while !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.close
end
6/13/2013Scripting with Ruby
Threading
require 'thread'
done        = false
socket      = TCPServer.open(3333)
connections = Queue.new
processor   = 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)
end
processor.join
socket.close
def process(connections, cfg)
  while !connections.empty?
    connection = connections.pop
    client = connection.get_client
    port, host, ipno = client.peeraddr[1..3]
    # Do stuff
  end
end
6/13/2013Scripting with Ruby
Database Access
require 'date'
require 'rubygems'
require 'dbi'
# Call database for data
dbhandle = DBI.connect("dbi:#{sss}", 'xxx', 'xxx')
rows = dbhandle.select_all("EXEC getTotals ?", 
ARGV[0])
if rows.nil? or rows.empty?
  puts "Nothing to report"
  exit
end
lines  = ['']
lines << "Your report for #{Date.today.to_s}"
lines << ''
rows.each do |row|
  lines << row['column_name']
end
6/13/2013Scripting with Ruby
Other Useful Modules
● Log files
require 'logger'
log = Logger.new(STDOUT)
log.level = Logger::WARN
log.debug( 'Created logger' )
log.info( 'Program started' )
log.warn( 'Nothing to do!' )
● Configuration files
config = File.open( 'report.yaml' ) { |yf| YAML::load( yf ) }
config = JSON.parse( IO.read( 'report.json' ) )
6/13/2013Scripting with Ruby
Gems
● XML Generation
✔ nokogiri
● PDF Generation
✔ prawn
● Events / Timers
✔ eventmachine
6/13/2013Scripting with Ruby
Test First
● The usual test frameworks can be used
➢ rspec, test::unit, minitest
C:UsersStuartClientswhbbiwhbbireports> rspec ­c ­fs trade­totals­email­spec.rb
TradeTotalsEmail
  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 in
Finished in 0.018 seconds
8 examples, 0 failures
6/13/2013Scripting with Ruby
exit(0)
Stuart Palmer
Silverado Consulting, Inc.
stuart@silveradosw.com
(408)529-6891

Weitere ähnliche Inhalte

Andere mochten auch

oGIP national products
oGIP national productsoGIP national products
oGIP national productsAIESECGreece
 
עמותת והדרת
עמותת והדרתעמותת והדרת
עמותת והדרתAlfred Cohen
 
הסמכות מטפל
הסמכות מטפלהסמכות מטפל
הסמכות מטפלAlfred Cohen
 
DIABETIC FOOT. Dr.Ajit Kumar Varma
DIABETIC FOOT.   Dr.Ajit Kumar VarmaDIABETIC FOOT.   Dr.Ajit Kumar Varma
DIABETIC FOOT. Dr.Ajit Kumar VarmaDr.Ajit Kumar Varma
 
Prepare to Preach (Session 1)
Prepare to Preach (Session 1)Prepare to Preach (Session 1)
Prepare to Preach (Session 1)Bong Baylon
 
Sales Presentation
Sales PresentationSales Presentation
Sales PresentationAIESECGreece
 
Business leadership: How to be a good leader?
Business leadership: How to be a good leader?Business leadership: How to be a good leader?
Business leadership: How to be a good leader?David Kiger
 
Solutions to Manage Hospital Parking Challenges and Customer Expectations
Solutions to Manage Hospital Parking Challenges and Customer ExpectationsSolutions to Manage Hospital Parking Challenges and Customer Expectations
Solutions to Manage Hospital Parking Challenges and Customer ExpectationsAndrew Vidor
 
Prepare to preach (ses 1)
Prepare to preach (ses 1)Prepare to preach (ses 1)
Prepare to preach (ses 1)Bong Baylon
 
Automatic water level controller
Automatic water level controllerAutomatic water level controller
Automatic water level controllerGeetha Smiley
 
Corporate Etiquette
Corporate EtiquetteCorporate Etiquette
Corporate EtiquetteAshit Jain
 
How to Create Engaging Data-driven stories
How to Create Engaging Data-driven storiesHow to Create Engaging Data-driven stories
How to Create Engaging Data-driven storiesBuzzSumo
 

Andere mochten auch (13)

oGIP national products
oGIP national productsoGIP national products
oGIP national products
 
עמותת והדרת
עמותת והדרתעמותת והדרת
עמותת והדרת
 
הסמכות מטפל
הסמכות מטפלהסמכות מטפל
הסמכות מטפל
 
DIABETIC FOOT. Dr.Ajit Kumar Varma
DIABETIC FOOT.   Dr.Ajit Kumar VarmaDIABETIC FOOT.   Dr.Ajit Kumar Varma
DIABETIC FOOT. Dr.Ajit Kumar Varma
 
Prepare to Preach (Session 1)
Prepare to Preach (Session 1)Prepare to Preach (Session 1)
Prepare to Preach (Session 1)
 
Sales Presentation
Sales PresentationSales Presentation
Sales Presentation
 
9 Step Business Sales Process
9 Step Business Sales Process9 Step Business Sales Process
9 Step Business Sales Process
 
Business leadership: How to be a good leader?
Business leadership: How to be a good leader?Business leadership: How to be a good leader?
Business leadership: How to be a good leader?
 
Solutions to Manage Hospital Parking Challenges and Customer Expectations
Solutions to Manage Hospital Parking Challenges and Customer ExpectationsSolutions to Manage Hospital Parking Challenges and Customer Expectations
Solutions to Manage Hospital Parking Challenges and Customer Expectations
 
Prepare to preach (ses 1)
Prepare to preach (ses 1)Prepare to preach (ses 1)
Prepare to preach (ses 1)
 
Automatic water level controller
Automatic water level controllerAutomatic water level controller
Automatic water level controller
 
Corporate Etiquette
Corporate EtiquetteCorporate Etiquette
Corporate Etiquette
 
How to Create Engaging Data-driven stories
How to Create Engaging Data-driven storiesHow to Create Engaging Data-driven stories
How to Create Engaging Data-driven stories
 

Ähnlich wie Ruby Scripting

Leveraging Open Source to Manage SAN Performance
Leveraging Open Source to Manage SAN PerformanceLeveraging Open Source to Manage SAN Performance
Leveraging Open Source to Manage SAN Performancebrettallison
 
Chef - industrialize and automate your infrastructure
Chef - industrialize and automate your infrastructureChef - industrialize and automate your infrastructure
Chef - industrialize and automate your infrastructureMichaël Lopez
 
Logging in dockerized environment
Logging in dockerized environmentLogging in dockerized environment
Logging in dockerized environmentYury Bushmelev
 
Catalyst - refactor large apps with it and have fun!
Catalyst - refactor large apps with it and have fun!Catalyst - refactor large apps with it and have fun!
Catalyst - refactor large apps with it and have fun!mold
 
PHP CLI: A Cinderella Story
PHP CLI: A Cinderella StoryPHP CLI: A Cinderella Story
PHP CLI: A Cinderella StoryMike Lively
 
Replacing Cron Jobs with EBS Concurrent Requests: Abandoning Rube Goldberg
Replacing Cron Jobs with EBS Concurrent Requests: Abandoning Rube GoldbergReplacing Cron Jobs with EBS Concurrent Requests: Abandoning Rube Goldberg
Replacing Cron Jobs with EBS Concurrent Requests: Abandoning Rube GoldbergDanny Bryant
 
Towards the perfect Drupal Dev Machine
Towards the perfect Drupal Dev MachineTowards the perfect Drupal Dev Machine
Towards the perfect Drupal Dev MachineKrimson
 
루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날Sukjoon Kim
 
Fluentd and Embulk Game Server 4
Fluentd and Embulk Game Server 4Fluentd and Embulk Game Server 4
Fluentd and Embulk Game Server 4N Masahiro
 
Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core ModuleKatie Gulley
 
Pro PostgreSQL, OSCon 2008
Pro PostgreSQL, OSCon 2008Pro PostgreSQL, OSCon 2008
Pro PostgreSQL, OSCon 2008Robert Treat
 
EG Reports - Delicious Data
EG Reports - Delicious DataEG Reports - Delicious Data
EG Reports - Delicious DataBenjamin Shum
 
Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!cloudbring
 
Scaling in Mind (Case study of Drupal Core)
Scaling in Mind (Case study of Drupal Core)Scaling in Mind (Case study of Drupal Core)
Scaling in Mind (Case study of Drupal Core)jimyhuang
 
Embulk, an open-source plugin-based parallel bulk data loader
Embulk, an open-source plugin-based parallel bulk data loaderEmbulk, an open-source plugin-based parallel bulk data loader
Embulk, an open-source plugin-based parallel bulk data loaderSadayuki Furuhashi
 
Profiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindProfiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindSam Keen
 
2010 Smith Scripting101
2010 Smith Scripting1012010 Smith Scripting101
2010 Smith Scripting101bokonen
 

Ähnlich wie Ruby Scripting (20)

Leveraging Open Source to Manage SAN Performance
Leveraging Open Source to Manage SAN PerformanceLeveraging Open Source to Manage SAN Performance
Leveraging Open Source to Manage SAN Performance
 
Chef - industrialize and automate your infrastructure
Chef - industrialize and automate your infrastructureChef - industrialize and automate your infrastructure
Chef - industrialize and automate your infrastructure
 
Logging in dockerized environment
Logging in dockerized environmentLogging in dockerized environment
Logging in dockerized environment
 
Catalyst - refactor large apps with it and have fun!
Catalyst - refactor large apps with it and have fun!Catalyst - refactor large apps with it and have fun!
Catalyst - refactor large apps with it and have fun!
 
PHP CLI: A Cinderella Story
PHP CLI: A Cinderella StoryPHP CLI: A Cinderella Story
PHP CLI: A Cinderella Story
 
Replacing Cron Jobs with EBS Concurrent Requests: Abandoning Rube Goldberg
Replacing Cron Jobs with EBS Concurrent Requests: Abandoning Rube GoldbergReplacing Cron Jobs with EBS Concurrent Requests: Abandoning Rube Goldberg
Replacing Cron Jobs with EBS Concurrent Requests: Abandoning Rube Goldberg
 
PHP 5 Sucks. PHP 5 Rocks.
PHP 5 Sucks. PHP 5 Rocks.PHP 5 Sucks. PHP 5 Rocks.
PHP 5 Sucks. PHP 5 Rocks.
 
Towards the perfect Drupal Dev Machine
Towards the perfect Drupal Dev MachineTowards the perfect Drupal Dev Machine
Towards the perfect Drupal Dev Machine
 
루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날
 
Fluentd and Embulk Game Server 4
Fluentd and Embulk Game Server 4Fluentd and Embulk Game Server 4
Fluentd and Embulk Game Server 4
 
Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core Module
 
Pro PostgreSQL, OSCon 2008
Pro PostgreSQL, OSCon 2008Pro PostgreSQL, OSCon 2008
Pro PostgreSQL, OSCon 2008
 
EG Reports - Delicious Data
EG Reports - Delicious DataEG Reports - Delicious Data
EG Reports - Delicious Data
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!
 
Project Automation
Project AutomationProject Automation
Project Automation
 
Scaling in Mind (Case study of Drupal Core)
Scaling in Mind (Case study of Drupal Core)Scaling in Mind (Case study of Drupal Core)
Scaling in Mind (Case study of Drupal Core)
 
Embulk, an open-source plugin-based parallel bulk data loader
Embulk, an open-source plugin-based parallel bulk data loaderEmbulk, an open-source plugin-based parallel bulk data loader
Embulk, an open-source plugin-based parallel bulk data loader
 
Profiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindProfiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / Webgrind
 
2010 Smith Scripting101
2010 Smith Scripting1012010 Smith Scripting101
2010 Smith Scripting101
 

Kürzlich hochgeladen

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Ruby Scripting

  • 1. Scripting with Ruby Stuart Palmer RubyJax 13 June 2013
  • 2. 6/13/2013Scripting with Ruby Why 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. 6/13/2013Scripting with Ruby Traditional Scripting  Shell scripts  sh, bash, csh, ksh  DOS batch files  .bat  SQL Jobs  SQL scripts in database
  • 4. 6/13/2013Scripting with Ruby Sample shell script #!/bin/tcsh # # Expects one parameter in mm/dd/yyyy format # setenv TOP /opt/sp setenv SBIN ${TOP}/sbin setenv LOG ${TOP}/log set 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 <<EOF exec getTotals '$1' go quit EOF # # See if there was any output # if ( ­z /tmp/total.out ) then    rm ­f /tmp/total.out    exit 0 endif # # Nice formatting # echo "" > /tmp/total.fax echo "Totals for $1" >> /tmp/total.fax echo "" >> /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.fax rm ­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} endif mv ­f /tmp/total.fax ${saveDir}/total.${tradeDate}
  • 5. 6/13/2013Scripting with Ruby What can Ruby do? Ruby Standard Library ✔ Numbers and Math ✔ Strings ✔ Regular expressions ✔ Collections ✔ Dates and Times ✔ Files and Directories ✔ Networking ✔ Threads
  • 6. 6/13/2013Scripting with Ruby My First Exposure to Ruby require 'rubygems' require 'roo' require 'fileutils' ss = 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. 6/13/2013Scripting with Ruby Sending email require 'net/smtp' # Send email Net::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   end end
  • 8. 6/13/2013Scripting with Ruby File functions and FTP require 'file' require 'fileutils' # Write to a file report_file = File.new('/tmp/report­new', 'w') lines.each do |line|   report_file.puts line end report_file.close FileUtils.mv('/tmp/report­new', '/opt/xxx/todays­report') # FTP the file ftp = Net::FTP.new('ftp.silveradosw.com') ftp.login('stuart@silveradosw.com', 'xxx') ftp.passive = true ftp.chdir('Reports') ftp.puttextfile('/tmp/report­new', 'todays_report') ftp.close
  • 9. 6/13/2013Scripting with Ruby File functions and FTP require 'file' require 'fileutils' require 'net/ftp' # Write to a file report_file = File.new('/tmp/report­new', 'w') lines.each do |line|   report_file.puts line end report_file.close FileUtils.mv('/tmp/report­new', '/opt/xxx/todays­report') # FTP the file ftp = Net::FTP.new('ftp.silveradosw.com') ftp.login('stuart@silveradosw.com', 'xxx') ftp.passive = true ftp.chdir('Reports') ftp.puttextfile('/tmp/report­new', 'todays_report') ftp.close
  • 10. 6/13/2013Scripting with Ruby Client / Server require 'socket' socket = TCPSocket.open('localhost', 3333) socket.puts('hello') socket.puts('what?') socket.puts('done') socket = TCPSocket.open('localhost', 3333) socket.puts('quit') require 'socket' socket = TCPSocket.new('localhost', 3333) done_listening = false while !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.close end
  • 11. 6/13/2013Scripting with Ruby Threading require 'thread' done        = false socket      = TCPServer.open(3333) connections = Queue.new processor   = 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) end processor.join socket.close def process(connections, cfg)   while !connections.empty?     connection = connections.pop     client = connection.get_client     port, host, ipno = client.peeraddr[1..3]     # Do stuff   end end
  • 12. 6/13/2013Scripting with Ruby Database Access require 'date' require 'rubygems' require 'dbi' # Call database for data dbhandle = DBI.connect("dbi:#{sss}", 'xxx', 'xxx') rows = dbhandle.select_all("EXEC getTotals ?",  ARGV[0]) if rows.nil? or rows.empty?   puts "Nothing to report"   exit end lines  = [''] lines << "Your report for #{Date.today.to_s}" lines << '' rows.each do |row|   lines << row['column_name'] end
  • 13. 6/13/2013Scripting with Ruby Other Useful Modules ● Log files require 'logger' log = Logger.new(STDOUT) log.level = Logger::WARN log.debug( 'Created logger' ) log.info( 'Program started' ) log.warn( 'Nothing to do!' ) ● Configuration files config = File.open( 'report.yaml' ) { |yf| YAML::load( yf ) } config = JSON.parse( IO.read( 'report.json' ) )
  • 14. 6/13/2013Scripting with Ruby Gems ● XML Generation ✔ nokogiri ● PDF Generation ✔ prawn ● Events / Timers ✔ eventmachine
  • 15. 6/13/2013Scripting with Ruby Test First ● The usual test frameworks can be used ➢ rspec, test::unit, minitest C:UsersStuartClientswhbbiwhbbireports> rspec ­c ­fs trade­totals­email­spec.rb TradeTotalsEmail   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 in Finished in 0.018 seconds 8 examples, 0 failures
  • 16. 6/13/2013Scripting with Ruby exit(0) Stuart Palmer Silverado Consulting, Inc. stuart@silveradosw.com (408)529-6891