Skip to content

Instantly share code, notes, and snippets.

@edance
Created May 31, 2017 15:54
Show Gist options
  • Save edance/a000e6577bdf27daf5d891fad4d6a75e to your computer and use it in GitHub Desktop.
Save edance/a000e6577bdf27daf5d891fad4d6a75e to your computer and use it in GitHub Desktop.
Encode and decode emoji 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