Gem 简单包装了一下 Emoji, Auto Link, Sanitize.clean

mimosa · 2014年02月28日 · 最后由 camel 回复于 2014年03月01日 · 4243 次阅读

simple_format

  • Translate emoji name or unicode to HTML images.
  • Auto Link url and email.
  • Clean HTML elements and attributes.

Installation

Add simple_format to your Gemfile.

gem 'simple_format'

Usage

require 'simple_format'
string = "This is a <span src='error'>:ruby:</span> <script type='text/javascript'>alert('Formater');</script>.\n\n Test Auto Link www.ruby-china.com\n\n[email protected]\n\nTest Emoji tag <a href=':cat:'>🍀</a>:ruby-china:."
SimpleFormat.h(string) # Emoji, Auto Link, Sanitize.clean
  • return
This is a <span src=\"error\">:ruby:</span> alert('Formater');.<br><br> Test Auto Link <a href=\"http://www.ruby-china.com\" target=\"_blank\">www.ruby-china.com</a><br><br><a href=\"mailto:[email protected]\">[email protected]</a><br><br>Test Emoji tag <a href=\"&lt;img%20class=%22emoji%22%20src=%22//l.ruby-china.com/assets/emojis/cat.png%22%20width=%2264%22%20height=%2264%22%20/&gt;\"><img class=\"emoji\" src=\"//l.ruby-china.com/assets/emojis/four_leaf_clover.png\" width=\"64\" height=\"64\"></a>:ruby-china:.
SimpleFormat.auto_link(string)
  • return
This is a <span src='error'>:ruby:</span> <script type='text/javascript'>alert('Formater');</script>.<br /><br /> Test Auto Link <a href='http://www.ruby-china.com' target='_blank'>www.ruby-china.com</a><br /><br /><a href='mailto:[email protected]'>[email protected]</a><br /><br />Test Emoji tag <a href=':cat:'>🍀</a>:ruby-china:.
SimpleFormat.replace_emoji_with_images(string, 24) # Default img size is 64
  • return
This is a <span src='error'>:ruby:</span> <script type='text/javascript'>alert('Formater');</script>.\n\n Test Auto Link www.ruby-china.com\n\[email protected]\n\nTest Emoji tag <a href='<img class=\"emoji\" src=\"//l.ruby-china.com/assets/emojis/cat.png\" width=\"24\" height=\"24\" />'><img class=\"emoji\" src=\"//l.ruby-china.com/assets/emojis/four_leaf_clover.png\" width=\"24\" height=\"24\" /></a>:ruby-china:.
SimpleFormat.clean(string, {elements: [], attributes: { all: [] }})
=> "This is a :ruby: alert('Formater');.\n\n Test Auto Link www.ruby-china.com\n\n[email protected]\n\nTest Emoji tag 🍀:ruby-china:."

很有趣,下次我做一些文本编辑的应用时应该有用!

Github 地址呢?求围观

虽然又是一个轮子,但Sanitize对任何有用户输入的网站都有用,能做更好有点难。 小吐槽一下,api 名字有点奇怪,不够简洁明了,直接 to_text, restrict_clean, relax_clean 多简单。 post 排版有点乱,看了也不知道替换规则。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号