One of the main things I started working on once the initial bot was out was refactoring. Refactoring is important. It’s a way of going back into your code, cleaning it up, making it easier to understand and more transparent. Refactoring also helps to DRY out code, meaning that you look at your code to see when and how you repeat yourself and take out that repetition.
In the bot, there are two main places to refactor based on methods that are called often. For a majority of the functions, I provided an array of responses or gifs as a variable. I then called
m.reply variable.sample. So instead of continuing to write this over and over again, I turned these actions into a method.
The method looks like this:
def reply_random(m, list)This is pretty easy to read but basically, the list is the array and so the method is to give a random reply based on the list given and replying with a random response from that list.
This is what a corresponding function now looks like:
on :message, /.*(coffee).*/i do |m|
reply_random m, [
The second method I created to DRY out the code was the second most common functionality. This is where there is an array of response that are either replies or actions and instead of writing out the whole process (as explained in this post about bot functionality) I created an action or reply response method, which operates similarly to the
def action_or_reply_response(m, list)
list = list.sample
if list.first == :action
and again, with this change, this is what the code looks like:
on :message, /.*morning.*/ do |m|
action_or_reply_response m, [
[:reply, "Good morning to you too!"],
[:reply, "it's a brand new day!"],
[:reply, "I'm sleepy today"],
[:action, "makes coffee"],
[:action, "*throws open all the windows* it's a glorious day today"]