Module: Slack::Messages::Formatting

Defined in:
lib/slack/messages/formatting.rb

Class Method Summary collapse

Class Method Details

Embed a link to a Slack channel in a message by channel ID



52
53
54
# File 'lib/slack/messages/formatting.rb', line 52

def channel_link(channel_id)
  "<##{channel_id}>"
end

.date(time, format: '{date_num} {time_secs}', link: nil, text: nil) ⇒ Object

Format a DateTime or Time object as a date and time in a Slack message



43
44
45
46
# File 'lib/slack/messages/formatting.rb', line 43

def date(time, format: '{date_num} {time_secs}', link: nil, text: nil)
  args = [time.to_i, format, link].compact
  "<!date^#{args.join('^')}|#{text || time}>"
end

.escape(message) ⇒ Object

Escape a message.



32
33
34
35
36
37
# File 'lib/slack/messages/formatting.rb', line 32

def escape(message)
  message
    .gsub('&', '&amp;')
    .gsub('>', '&gt;')
    .gsub('<', '&lt;')
end

.markdown(text) ⇒ Object

Converts text from basic markdown into Slack’s mishmash



76
77
78
79
80
81
82
83
# File 'lib/slack/messages/formatting.rb', line 76

def markdown(text)
  text
    .gsub(/(?<!\*)\*([^*]+)\*(?!\*)/, '_\1_') # italic
    .gsub(/\*\*\*(.*?)\*\*\*/, '*_\1_*') # bold & italic
    .gsub(/\*\*(.*?)\*\*/, '*\1*') # bold
    .gsub(/~~(.*?)~~/, '~\1~') # strikethrough
    .gsub(/\[(.*?)\]\((.*?)\)/, '<\2|\1>') # links
end

.unescape(message) ⇒ Object

Unescape a message.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/slack/messages/formatting.rb', line 10

def unescape(message)
  CGI.unescapeHTML(message.gsub(/[“”]/, '"')
    .gsub(/[‘’]/, "'")
    .gsub(/<(?<sign>[?@#!]?)(?<dt>.*?)>/) do
      sign = Regexp.last_match[:sign]
      dt = Regexp.last_match[:dt]
      rhs = dt.split('|', 2).last
      case sign
      when '@', '!'
        "@#{rhs}"
      when '#'
        "##{rhs}"
      else
        rhs
      end
    end)
end

Embed a URL with custom link text in a message



68
69
70
# File 'lib/slack/messages/formatting.rb', line 68

def url_link(text, url)
  "<#{url}|#{text}>"
end

Embed a link to a user in a message by user ID



60
61
62
# File 'lib/slack/messages/formatting.rb', line 60

def user_link(user_id)
  "<@#{user_id}>"
end