微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – 如何在Ruby中限制Markdown语法?

我希望使用诸如 MarakuKramdown之类的Ruby库在Rails CMS评论系统中实现Markdown.我需要限制用户可以提交哪些Markdown功能.在此系统中,不允许用户插入图像,html或执行任何繁重的编辑,但强调和超链接是可以的.

基本上,我希望创建类似于this Textile filter的东西,但是对于Markdown语法.

解决方法

我在markdown trasformation之后使用第二步来使用 sanitize gem清理数据.它基于白名单并且非常易于配置,你可以很容易地实现你的目标.

为了节省你一些时间,这是我的文本格式化模块,希望它可以帮助你.内置的宽松规则对我来说有点过于严格.

module textformatter
  require 'sanitize'

  module Formatters
    MARKDOWN = 1
    TEXTILE = 2
  end

  RELAXED = {
      :elements => [
        'a','b','blockquote','br','caption','cite','code','col','colgroup','dd','dl','dt','em','i','img','li','ol','p','pre','q','small','strike','strong','sub','sup','table','tbody','td','tfoot','th','thead','tr','u','ul','del','ins','h1','h2','h3','h4','h5','hr','kbd'],:attributes => {
        'a'          => ['href','title'],'blockquote' => ['cite'],'col'        => ['span','width'],'colgroup'   => ['span','img'        => ['align','alt','height','src','title','ol'         => ['start','type'],'q'          => ['cite'],'table'      => ['summary','td'         => ['abbr','axis','colspan','rowspan','th'         => ['abbr','scope','ul'         => ['type']
      },:protocols => {
        'a'          => {'href' => ['ftp','http','https','mailto',:relative]},'blockquote' => {'cite' => ['http','img'        => {'src'  => ['http','q'          => {'cite' => ['http',:relative]}
      }
    }



  def self.to_html(text,formatter = Formatters::MARKDOWN)
    return "" unless text

    html = case formatter 
           when Formatters::MARKDOWN then
             Rdiscount.new(text,:smart).to_html
           when Formatters::TEXTILE then
             RedCloth.new(text).to_html
           end

    Sanitize.clean(html,RELAXED) 
  end
end

原文地址:https://www.jb51.cc/ruby/270114.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐