I think this piece of code replaces invalid UTF-8 characters with blank strings:
title = title.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
What is the second argument 'binary' for? Is it necessary?
According to the Ruby documentation for encode the 2nd argument is the encoding of the source string.
This may be an optional field, because there are 3 forms of this method:
encode(encoding [, options] ) → str
encode(dst_encoding, src_encoding [, options] ) → str
encode([options]) → str
You may need it, depending on what the source string looks like however: