Gem which enable encoding and decoding strings with 4 bytes chars like Emoji to save into 2 bytes databases (For example: Default setup of Mysql DB).
Usage was tested with Ruby on Rails 5.2. It should work with Rails 4 or Rails 6 too.
gem install emoji_encoder
Or add this to your Gemfile
gem 'emoji_encoder'
class Review < ApplicationRecord
extend EmojiEncoder
attrs_for_emoji :subject, :description
# This piece of code add callback on save instance of class which call encode_subject and encode_description to transform 4 bytes chars to 2 bytes chars which allow save text as 'standard' text with 2 bytes chars
# This piece of code add method for decode saved text too: decode_subject and decode_description. Use these method everywhere you want to show decoded text with 4 bytes chars (Emoji).
end
#apps/reviews/form.html.slim
= bootstrap_form_for review, layout: :inline, class: "", remote: true do |f|
= f.text_field :subject, hide_label: true, input_group_class: 'input-group-sm', value: f.object.decode_subject
= f.text_field :description, hide_label: true, input_group_class: 'input-group-sm', value: f.object.decode_description
Some databases do not allow 4bytes chars in tables or can not be switched to 4B chars because of production DB server. This gem resolve issue like 'Mysql2::Error: Incorrect string value: \xF0\x9F\xA5\x82 for column' without pain.