Lチカ開発ブログ

https://l-chika.com/の開発ブログ

RubyでMarkdownのImgタグのサイズ指定

Markdownエディタを作成したので、次は表示をつくる。

l-chika.hatenablog.com

前提

以下のGemを利用

実現したい事

![image](http://url.to/image.png = 250x250)

![image](http://url.to/image.png = 250x)

のようなMarkdownを、

<img src="http://url.to/image.png" height="250px" width="250px">
<img src="http://url.to/image.png" height="250px">

と、したい

参考

Resize image in the wiki of GitHub using Markdown - Stack Overflow

実装

Decorator

class HogeDecorator < Draper::Decorator
  ...
  def markdown_content
    markdown = Redcarpet::Markdown.new(CustomRender.new(with_toc_data: true),
                                       autolink: true, space_after_headers: true, tables: true, fenced_code_blocks: true)
    markdown.render(object.content).html_safe
  end
  ...
end
...
class CustomRender < Redcarpet::Render::HTML
  def image(link, title, alt_text)
    if link =~ /(.*)=(\d+)x(\d+|)/
      "<img src='#{$1.strip}' width='#{$2}px' height='#{$3}px' title='#{title}' alt='#{alt_text}'>"
    else
      "<img src='#{link}' title='#{title}' alt='#{alt_text}'>"
    end
  end
end

view

   <div>
      <%= @hoge.markdown_content %>
   </div>

参考

こんなアプローチもあった

ruby on rails - Markdown external image links with Redcarpet - Stack Overflow

Easier Image Markup With Redcarpet