about summary refs log tree commit diff
path: root/app/lib/emoji.rb
blob: 6de70e9b4127cb5f4ab7a213d179aedd6d9e4b32 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# frozen_string_literal: true

require 'singleton'

class Emoji
  include Singleton

  def initialize
    data = Oj.load(File.open(File.join(Rails.root, 'lib', 'assets', 'emoji.json')))

    @map = {}

    data.each do |_, emoji|
      keys    = [emoji['shortname']] + emoji['aliases']
      unicode = codepoint_to_unicode(emoji['unicode'])

      keys.each do |key|
        @map[key] = unicode
      end
    end
  end

  def unicode(shortcode)
    @map[shortcode]
  end

  def names
    @map.keys
  end

  private

  def codepoint_to_unicode(codepoint)
    if codepoint.include?('-')
      codepoint.split('-').map(&:hex).pack('U*')
    else
      [codepoint.hex].pack('U')
    end
  end
end