Created
August 12, 2017 07:45
-
-
Save icyflame/0173f5c1a1779b72d794b02f3f0507af to your computer and use it in GitHub Desktop.
the ActionView::Helpers::TextHelper simple_format function for use outside Rails apps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'action_view' | |
NOTICE_ATTRIBS = 5 | |
TOP_NOTICES = 5 | |
# https://apidock.com/rails/v4.2.1/ActionView/Helpers/TextHelper/split_paragraphs | |
def split_paragraphs(text) | |
return [] if text.blank? | |
text.to_str.gsub(/\r\n?/, "\n").split(/\n\n+/).map! do |t| | |
t.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') || t | |
end | |
end | |
# https://github.com/rails/rails/blob/0732ea7136da43cf3d84d8ce20dd7105a16e78b0/actionview/lib/action_view/helpers/text_helper.rb#L300 | |
def simple_format(text, html_options = {}, options = {}) | |
obj = ActionView::Base.new | |
wrapper_tag = options.fetch(:wrapper_tag, :p) | |
text = obj.sanitize(text) if options.fetch(:sanitize, true) | |
paragraphs = split_paragraphs(text) | |
if paragraphs.empty? | |
obj.content_tag(wrapper_tag, nil, html_options) | |
else | |
paragraphs.map! { |paragraph| | |
obj.content_tag(wrapper_tag, obj.raw(paragraph), html_options) | |
}.join("\n\n").html_safe | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment