Class: Magnet::Markdown::Filter::Emoji

Inherits:
HTML::Pipeline::Filter
  • Object
show all
Defined in:
lib/magnet/markdown/filter/emoji.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.emojisObject



5
6
7
# File 'lib/magnet/markdown/filter/emoji.rb', line 5

def self.emojis
  Emoji.all.map(&:aliases).flatten.sort
end

.img_tagObject



13
14
15
# File 'lib/magnet/markdown/filter/emoji.rb', line 13

def self.img_tag
  '<img class="emoji" alt=":%{name}:" title=":%{name}:" style="width: 1em; height: 1em;" align="absmiddle" src="%{src}">'
end

.regexp_patternObject



9
10
11
# File 'lib/magnet/markdown/filter/emoji.rb', line 9

def self.regexp_pattern
  @regexp_pattern ||= /:(?<name>#{ (emojis.map { |n| Regexp.escape(n) }).join('|') }):/xo
end

Instance Method Details

#callObject



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/magnet/markdown/filter/emoji.rb', line 17

def call
  doc.search('text()').each do |node|
    content = node.to_html
    next unless content.include?(':')
    next if has_ancestor?(node, %w(pre code tt))
    html = emojify(content)
    next if html == content
    node.replace(html)
  end
  doc
end

#emoji_filename(emoji_name) ⇒ Object



52
53
54
# File 'lib/magnet/markdown/filter/emoji.rb', line 52

def emoji_filename(emoji_name)
  Emoji.find_by_alias(emoji_name).image_filename
end

#emojify(html) ⇒ Object



33
34
35
36
37
38
# File 'lib/magnet/markdown/filter/emoji.rb', line 33

def emojify(html)
  html.gsub(self.class.regexp_pattern) do |_match|
    name = Regexp.last_match['name']
    self.class.img_tag % { name: name, src: src_url(name) }
  end
end

#src_path(emoji_name) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/magnet/markdown/filter/emoji.rb', line 44

def src_path(emoji_name)
  if context[:emoji_path]
    context[:emoji_path].sub(':filename', emoji_filename(emoji_name))
  else
    File.join('emoji', emoji_filename(emoji_name))
  end
end

#src_url(emoji_name) ⇒ Object



40
41
42
# File 'lib/magnet/markdown/filter/emoji.rb', line 40

def src_url(emoji_name)
  File.join(context[:emoji_root], src_path(emoji_name))
end

#validateObject



29
30
31
# File 'lib/magnet/markdown/filter/emoji.rb', line 29

def validate
  needs :emoji_root
end