Automate Your Boring Tasks with Ruby
If you aren't already fed up with doing the same boring stuff over and over again, you will In the long run. Tasks which are repeated again and again in the same manner, such as System administration tasks, such as uploading your codebase, adjusting settings, repeatedly running commands, etc. tend to sap the enthusiasm you experience when working on your project.
In this article you'll learn how you can automate your boring stuff using Ruby, while understanding the fundamentals necessary to do so.
Introduction to Ruby
Yukihiro Matsumoto, a computer scientist and software developer, invented Ruby in the mid-1990s, an open-source programming language. Because of this, frameworks like Ruby on Rails could be built on top of it. Ruby has an expressive and easy-to-use, dynamic and free format programming language syntax, one of the major reasons it is widely adopted and loved.
It is an interpreted language, like Python, as opposed to a compiled one like C or C++. Ruby is distinct from other programming languages due to the fact that it hides a lot of information from the programmer. This makes programming in Ruby far easier than in more complex mainstream languages such as C or C++. It does suggest, though, that finding errors in the code may be more challenging.
Ruby code can work on all major operating platforms, including Windows, macOS, and Linux, without requiring porting.
Language Fundamentals
Some of Ruby's built-in functions are one-of-a-kind. It is possible, for instance, that new methods can be declared at application runtime. As with developing code, you don't need to know everything or have all the details worked out before you can begin. Automation scripts can be written more quickly and easily as a result of this.
Below is a simple example showcasing basics of the Ruby language:
puts "Please submit your current age: "
age = gets
puts "Your current age is: #{age}"
The above code can be written and stored in a file with an extension .rb
, or can be directly written line by line in the Interactive Ruby (irb) shell, an interactive programming environment that comes with Ruby.
Automation Examples with Ruby
One of the greatest advantages of using Ruby is, it's ability to scale down the efforts and the code required to automate complex scenarios by scripting into reusable tasks and code. Let's have a look at the examples and learn how you can leverage the power of scripting to automate your boring stuff with Ruby.
Schedule TODOs into Microsoft Outlook Tasks
As a developer, there would be frequent instances when you would be required to interrupt your work and save your TODOs to be completed later, and almost every time you'd be required to adhere to the deadlines. So how can you ensure that you don't miss any of the deadlines and get your work done?
Ruby to the rescue! The below script showcases how you can automatically schedule your pending TODOs into Microsoft Outlook and get reminded to complete them:
require 'win32ole'
outlookApp = WIN32OLE.new('Outlook.Application')
Dir.glob('**/*.rb').each do |file|
lines = File.readlines(file)
matchstring = /#\s*(TODO):?\s*(.*)\s*$/
lines.each_with_index do |line, n|
if match = line.scan(matchstring).first
schedule = outlookApp.CreateItem(3)
schedule.Subject = "To be completed: %s" % match
details = []
details << "%s, line %d:\n" %
[
File.join(Dir.pwd, file),
n + 1
]
selection = [n - 5, 0].max...[n + 5, lines.size].min
details.push selection.map do |index|
"%5d: %s" % [i + 1, lines[i]]
end
schedule.Body = details.join
schedule.Save
end
end
end
Let's understand the above code snippet. First of all, require
declares that this Ruby file requires an import module named win32ole
to make the code work. win32ole
represents OLE Automation in Ruby, using which you can access OLE to run applications like VBScript. In the next line, outlookApp
is declared which initializes WIN32OLE
.
Dir.glob
returns the filenames found by expanding pattern, which is .rb
(Ruby) files in the directory. Once found, File.readlines
method reads the contents of each of the file inside .each do |file|
and lines.each_with_index
iterates through the source code keeping track of the line numbers.
The if
block matches each of the line
with the TODO
string, specified in matchstring
variable. Every time the line is matched, schedule
variables create a new task in the Microsoft Outlook with a subject line from the matched string. Then, The code snippet and file name are added using the details
variable which adds the data to the body of the newly created task in Microsoft Outlook.
Finally, schedule.Save
saves the newly created task in Microsoft Outlook tasks list.
Send Weather Updates via Email
Suppose you want to check the weather for different cities that you're traveling to in the near future. The below Ruby script showcases how you can make use of Ruby's weather capabilities as well as how you can send a simple email message using the Ruby mail API.
require 'net/http'
require 'json'
require 'net/smtp'
def do_weather_query(city, api_key)
uri = URI("https://api.openweathermap.org/data/2.5/weather?q=#{city}&appid=#{api_key}")
response = Net::HTTP.get(uri)
results = JSON.parse(response)
return results
end
def get_weather_for_city(city, api_key)
weather_info = do_weather_query(city, api_key) # replace with your API key obtained from here: https://openweathermap.org/api
city = weather_info[:name]
temp = weather_info[:main][:temp]
humidity = weather_info[:main][:humidity]
description = weather_info[:main][:weather][:description]
return "#{city}: \n" +
"Currently #{temp} degrees, #{humidity}% humidity, with #{description}"
end
class SendEmail < Net::SMTP
def initialize(options)
super
@user = options["user"]
@from = options["from"]
@to = options["to"].to_a
@pass = options["pass"]
@server = options["server"]
@subject = options["subject"]
end
def body=(mail_body)
time_foo = Time.new.httpdate
@body = "From: #{@from} <#{@from}>\n"
@body << "To: #{@to}<#{@to}>\n"
@body << "Subject: #{@subject}\n"
@body << "Date: #{time_foo}\n"
@body << "Importance:high\n"
@body << "MIME-Version:1.0\n"
@body << "\n\n\n"
@body << mail_body
end
def sendmail
smtp = Net::SMTP.start(@server, 25)
smtp.send_message @body, @from, @to
smtp.finish
end
end
weather_string = ''
maildata = Hash.new
maildata["from"] = ""
maildata["to"] = ""
maildata["server"] = ""
maildata["subject"] = "Today's weather in places I'm visiting"
mail = SendMail.new(maildata)
mail.body = get_weather_for_city("London", xxxxxxxx)
mail.send
Conclusion
Ruby can be used to automate a wide range of jobs. Automated test cases, machine inspections – just to name a few of the many duties you do on a regular basis. If you have the proper tools and an understanding of scripting standards, you can easily automate these activities using Ruby. Using this tool, you may push their creativity and come up with one-of-a-kind automated solutions to the tedious tasks they experience on a regular basis.