Skip to content

Instantly share code, notes, and snippets.

@icyflame
Created August 12, 2017 07:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icyflame/0173f5c1a1779b72d794b02f3f0507af to your computer and use it in GitHub Desktop.
Save icyflame/0173f5c1a1779b72d794b02f3f0507af to your computer and use it in GitHub Desktop.
the ActionView::Helpers::TextHelper simple_format function for use outside Rails apps
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