0

I have a Portfolio model that contains a comments field of type text, whose values are a set of paragraphs delimited by some combo of cr and nl characters. The objective is to extract the paragraphs into an array, wrap them in <p> tags, and rejoin them for output to the browser; so the focus in the code below is lines 6-8.

The problem I'm having is that the < and > characters are getting rendered as HTML entities &lt; and &gt;.

I'm new to Ruby and Rails, so my guess is that the reason this isn't working as intended is because I'm probably taking an incorrect approach--and I'd like to know how an experienced Ruby coder would address this sort of situation. How do you insert HTML tags into content before you send it to a view? Or is that always a violation of the MVC model--in which case, what's a correct way to solve this sort of problem?

Here's the code:

1.   module ApplicationHelper
2.   
3.     def portfolio_featured
4.       @portfolios = Portfolio.all
5.       @portfolios.each do |p|
6.         paras = p.comments.split(/\r?\n\r?\n/)
7.         paras.collect! { |p| "<p>" + p + "</p>" }
8.         p.comments = paras.join
9.       end
10.    end
11.
12.  end

2 Answers 2

1

take a look at simple_format TextHelper.

It is probably what you are looking for.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That had exactly the effect I was looking for. So what I've done here--inserting HTML tags in a helper--does that not compromise the MVC framework?
I don't think it compromises the mvc framework, you was just trying to reinventing the wheel, that was not necessary as you can see. Please consider accept my answer as correct. Glad it helps you!
0

You can use TextHelper#simple_format or something fancy like Bluecloth (Markdown), but if you want to cook it yourself, that's what you can write (the key is using safe_join):

def portfolio_featured
   safe_join(Portfolio.all.map do |portfolio|
     portfolio.comments.lines.map { |line| content_tag(:p, line.chomp) }
   end)
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.