Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coping with "string contains null byte" sent from users

I have an API controller that receives information about a media file's path and id3 tags, and saves them to an Active Record instance, using PostgreSQL/Rails.

Sometimes however the user sends strings such as:

"genre"=>"Hip-Hop\u0000Hip-Hop/Rap" 

and Rails/Postgres aren't exactly happy about that when trying to persist on save:

An ArgumentError occurred in internals#receive:   string contains null byte  activerecord (3.2.21) lib/active_record/connection_adapters/postgresql_adapter.rb:1172:in `send_query_prepared' 

How can I clean this string in Ruby to completely remove null bytes?

like image 366
John Smith Avatar asked Mar 28 '15 17:03

John Smith


1 Answers

The gsub method on String is probably suitable. You can just do string.gsub("\u0000", '') to get rid of them.

http://ruby-doc.org/core-2.1.1/String.html#method-i-gsub

like image 74
tpbowden Avatar answered Sep 24 '22 07:09

tpbowden