Better simple_format for Rails 3.X projects

Since Rails 3.0 came out, we Rails devs deal with the auto escaping of HTML.

Now, in most cases it comes in SUPER handy, but not always.

Rails has an answer to that, it’s called ‘simple_format’, and it escapes the HTML and formats the string to be friendly, with line breaks, etc…

Now, the problem with simple_format is that it wraps everything with a paragraph tag, which doens’t always fit your design, your markup or just your sense of aesthetics.

So, I wrote a REALLY simple helper, not even going to explain it because it is so simple

[ruby]

def simple_format_no_tags(text, html_options = {}, options = {})

text = ” if text.nil?

text = smart_truncate(text, options[:truncate]) if options[:truncate].present?

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)(?=[^\n])/, ‘\1
’) # 1 newline -> br

text.html_safe

end

[/ruby]

As you can see, it does not wrap with any tag, also it adds an option to truncate the string.

Submit to Hacker News

[NOTE] This post has been imported to Hugo from a Wordpress blog. It may be broken, missing images, code snippets or other information.

[NOTE] updated March 6, 2012. It's 2519 days old . This article may have outdated content.