加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:08:34 所属栏目:百科 来源:网络整理
导读:我希望使用诸如 Maraku或 Kramdown之类的Ruby库在Rails CMS评论系统中实现Markdown.我需要限制用户可以提交哪些Markdown功能.在此系统中,不允许用户插入图像,html或执行任何繁重的编辑,但强调和超链接是可以的. 基本上,我希望创建类似于this Textile filter
我希望使用诸如 Maraku或 Kramdown之类的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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读