# Block syntax
This:
loop
{
...
}
Causes a syntax error in MRI 2.1. This would fix the syntax error:
loop {
...
}
However, the use of `{...}` is normally reserved for single-line blocks. Prefer:
loop do
..
end
# Methods
Use many more methods. It should be possible to figure out what the script does, in broad strokes, by looking only at its main method. Find lines of code that _do one thing_ and put them in their own method. For example:
def login_to_se
login_form = $agent.get('https://openid.stackexchange.com/account/login').forms.first
login_form.email = email
login_form.password = password
$agent.submit login_form, login_form.buttons.first
puts 'logged in with SE openid'
end
...
login_to_se
and so on. Your methods should, when possible, have these properties:
* The method does one thing
* The name says what it does
* All of the code in the method is at the _same level of abstraction_
You want code, at the higher levels such as the main loop, to look more like this:
loop do
continue_on_error do
login_to_se
login_to_meta
login_to_chat
loop do
copy_new_post_to_chat
wait
end
end
end
A method should read like a story. Abstract away--in methods, classes, etc--details that make the story hard to follow.
# Abstract out rescue, too
You may notice the call to `continue_on_error` above. It can be very useful to abstract out your rescue blocks, too. In this case, it gives us a method name that documents _why_ we are doing the rescue:
def continue_on_error
yield
rescue => e
$ERR = e
p e
end
# $ERR
We can get rid of $ERR by having #continue_on_error say that we're restarting:
def continue_on_error
yield
rescue => e
puts e
puts "Restarting"
end
and in the main loop, instead of:
puts $ERR ? "An unknown error occurred. Bot restarted." : "Bot initialized."
simply
puts "Initialized"
The script's log output will be just as clear.