Class: MarkdownToMrkdwn::Converter
- Inherits:
-
Object
- Object
- MarkdownToMrkdwn::Converter
- Defined in:
- lib/markdown_to_mrkdwn/converter.rb
Constant Summary collapse
- SENTINEL =
"§"
Instance Method Summary collapse
- #convert(markdown) ⇒ Object
-
#initialize(heading: :bold, keep_hr: false) ⇒ Converter
constructor
Options: - heading: :bold (default) or :plain - keep_hr: true to keep — as is (default false -> replace with an em dash line).
Constructor Details
#initialize(heading: :bold, keep_hr: false) ⇒ Converter
Options:
-
heading: :bold (default) or :plain
-
keep_hr: true to keep — as is (default false -> replace with an em dash line)
9 10 11 12 |
# File 'lib/markdown_to_mrkdwn/converter.rb', line 9 def initialize(heading: :bold, keep_hr: false) @heading_style = heading @keep_hr = keep_hr end |
Instance Method Details
#convert(markdown) ⇒ Object
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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/markdown_to_mrkdwn/converter.rb', line 14 def convert(markdown) return "" if markdown.nil? || markdown.empty? text = markdown.dup # 1) Extract fenced code blocks and inline code to protect from further processing blocks = {} text = extract_fenced_code_blocks(text, blocks) text = extract_inline_code(text, blocks) # 2) Images:  -> <url|alt> text.gsub!(/!\[(.*?)\]\((\S+?)(?:\s+".*?")?\)/) do alt = Regexp.last_match(1) url = Regexp.last_match(2) "<#{url}|#{alt}>" end # 3) Links: [text](url) -> <url|text> text.gsub!(/\[(.*?)\]\((\S+?)(?:\s+".*?")?\)/) do label = Regexp.last_match(1) url = Regexp.last_match(2) "<#{url}|#{label}>" end # 4) Strikethrough: ~~text~~ -> ~text~ text.gsub!(/~~(.*?)~~/, '~\1~') # 5) Italic: *text* or _text_ -> _text_ # Run italics BEFORE bold so that bold remains asterisks in Slack. # Only match single markers, not double. text.gsub!(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/, '_\1_') text.gsub!(/(?<!_)_(?!_)(.+?)(?<!_)_(?!_)/, '_\1_') # 6) Bold: **text** or __text__ -> *text* text.gsub!(/\*\*(.+?)\*\*/, '*\1*') text.gsub!(/__(.+?)__/, '*\1*') # 7) Headings: # H -> *H* text = convert_headings(text) # 8) Horizontal rules text.gsub!(/^\s*([-*_])\s*\1\s*\1\s*$/, @keep_hr ? '\0' : "—\n") # 9) Restore protected code segments restore_placeholders(text, blocks) end |