仅从 Ruby 中的字符串中删除表情符号

Remove only emoticons from string in Ruby

一位用户正在使用表情符号,它使我的应用程序出错。如何检查字符串是否包含表情符号并仅删除表情符号?

 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

发生这种情况是因为您的数据库不允许使用 utf8mb4,因此您需要同时检查 return 文本。我会将检查作为回调进行,并且仅当文本字段已更改时才能减少调用回调的次数。

 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