Module: MCMarkdown::Formatter::Image

Included in:
Base
Defined in:
lib/mc_markdown/formatters/image.rb

Constant Summary collapse

IMG_ATTRIBUTES_PATTERN =

rubular.com/r/lss0C9HqoP $1 => alt $2 => class/attrs

/^ ([^_{}]+)? (?:{(.+?)})? \s?$/x

Instance Method Summary collapse

Instance Method Details

#image(link, title, alt_text) ⇒ Object

add classes to images and render title as figure/figcaption ![alt class](/path/to/img.jpg “caption”)



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
# File 'lib/mc_markdown/formatters/image.rb', line 12

def image link, title, alt_text
  return "![#{alt_text}](#{link}#{(title && !title.empty?) ? " \"#{title}\"" : ''})" if extensions[:no_images]

  match_data = IMG_ATTRIBUTES_PATTERN.match (alt_text || "")
  alt_text = match_data[1] || ""
  attrs    = match_data[2] || ""

  # check for attrs in class field
  if attrs.include? ':'
    attrs = attrs.split(', ').each_with_object([]) do |frag, out|
      frag = frag.split ':'
      out.push "#{frag[0].strip}='#{frag[1].strip}'"
      out
    end.join(" ") + " "
  elsif !attrs.empty?
    classes = attrs
    attrs   = "class='#{attrs}' "
  end

  if title
    return "<figure class='img #{classes}'>" +
           "<img src='#{link}' alt='#{alt_text.strip}' />" +
           "<figcaption>" + ::Redcarpet::Markdown.new( self ).render(title).strip + "</figcaption>" +
           "</figure>"
  else
    return "<img src='#{link}' alt='#{alt_text.strip}' #{attrs}/>"
  end
end

#postprocess(doc) ⇒ Object

need to strip paragraph tags from around figures, has potential to cause invalid markup



43
44
45
46
47
48
49
50
51
# File 'lib/mc_markdown/formatters/image.rb', line 43

def postprocess doc
  doc = doc.gsub( /<p><figure/, '<figure' ).gsub( /<\/figure><\/p>/, '</figure>' )

  if defined?(super)
    return super(doc)
  else
    return doc
  end
end