Skip to content

Instantly share code, notes, and snippets.

@masak2009
Last active May 27, 2020 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masak2009/133a73962ca199543f5b9c88c37a81c1 to your computer and use it in GitHub Desktop.
Save masak2009/133a73962ca199543f5b9c88c37a81c1 to your computer and use it in GitHub Desktop.

Emoji Encoder

Introdution

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).

Note

Usage was tested with Ruby on Rails 5.2. It should work with Rails 4 or Rails 6 too.

Installation

gem install emoji_encoder

Or add this to your Gemfile

gem 'emoji_encoder'

Adding emoji_encoder functionality to an Active Record Model

  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

Why this gem was created?

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment