Created
May 31, 2017 15:54
-
-
Save edance/a000e6577bdf27daf5d891fad4d6a75e to your computer and use it in GitHub Desktop.
Encode and decode emoji unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Emoji | |
# Emojis found from link below | |
# https://raw.githubusercontent.com/omnidan/node-emoji/master/lib/emoji.json | |
SYMBOL_LOOKUP = JSON.parse(File.read("#{Rails.root}/emoji.json")) | |
STRING_LOOKUP = SYMBOL_LOOKUP.invert | |
ALL_REGEXP = Regexp.union(STRING_LOOKUP.keys) | |
def find(symbol) | |
SYMBOL_LOOKUP[symbol.to_s] | |
end | |
def find_by_string(str) | |
STRING_LOOKUP[str] | |
end | |
def encode(str) | |
str.gsub(ALL_REGEXP) { |m| ":#{find_by_string(m)}:" } | |
end | |
def decode(str) | |
str.gsub(/:([^\s:]?[\w-]+):/) do |match| | |
(find(Regexp.last_match(1)) || match).to_s | |
end | |
end | |
module_function :find, :find_by_string, :encode, :decode | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment