Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove only emoticons from string in Ruby

A user is using an emoticon and it is erroring out my app. How can I get check if the string contains an emoticon and remove only the emoticon?

 Message.create(user: @user, ticket: @ticket, text: "\r\nIm done with this bug! \u{1f431}!\r\n")

 ActiveRecord::StatementInvalid: Mysql2::Error: Incorrect string value: 'x90\xB1!\x0D
like image 742
James McCarthy Avatar asked Aug 24 '26 05:08

James McCarthy


1 Answers

This is occuring because your database doesnt allow for utf8mb4 so you need to check for both and return the text. I would do the check as a callback and only if the text field has changed in order to reduce the number of times the callback is called.

 before_save :ensure_utf8, if: :text_changed?

def ensure_utf8
   if self.text
      self.text = self.text.encode( Encoding.find('UTF-8'), { invalid: :replace, undef: :replace, replace: '' } )
      self.text = self.text.each_char.select { |c| c.bytes.first < 240 }.join('')
   end
end
like image 58
John Pollard Avatar answered Aug 26 '26 23:08

John Pollard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!