Skip to content
Browse files

simple_format refactoring

using split_paragraphs method and content_tag instead of string
concatination
  • Loading branch information...
1 parent c13a3f0 commit 09fcac95d7d263b054fa0c9a168da2789ce8ae06 @KensoDev KensoDev committed
Showing with 17 additions and 9 deletions.
  1. +17 −9 actionpack/lib/action_view/helpers/text_helper.rb
View
26 actionpack/lib/action_view/helpers/text_helper.rb
@@ -259,16 +259,16 @@ def word_wrap(text, *args)
# simple_format("<span>I'm allowed!</span> It's true.", {}, :sanitize => false)
# # => "<p><span>I'm allowed!</span> It's true.</p>"
def simple_format(text, html_options={}, options={})
- text = '' if text.nil?
- text = text.dup
- start_tag = tag('p', html_options, true)
text = sanitize(text) unless options[:sanitize] == false
- text = text.to_str
- text.gsub!(/\r\n?/, "\n") # \r\n and \r -> \n
- text.gsub!(/\n\n+/, "</p>\n\n#{start_tag}") # 2+ newline -> paragraph
- text.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br
- text.insert 0, start_tag
- text.html_safe.safe_concat("</p>")
+ paragraphs = split_paragraphs(text)
+
+ if paragraphs.empty?
+ content_tag('p', nil, html_options)
+ else
+ paragraphs.map { |paragraph|
+ content_tag('p', paragraph, html_options, options[:sanitize])
+ }.join("\n\n").html_safe
+ end
end
# Creates a Cycle object whose _to_s_ method cycles through elements of an
@@ -413,6 +413,14 @@ def set_cycle(name, cycle_object)
@_cycles = Hash.new unless defined?(@_cycles)
@_cycles[name] = cycle_object
end
+
+ 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
end
end
end

0 comments on commit 09fcac9

Please sign in to comment.
Something went wrong with that request. Please try again.