John Curry John Curry - 4 years ago 81
HTML Question

word wrapping in rails 4 app not working at all

I'm trying to wrap this which is in my views directory, and part of a skills.each do |skill| :

<%= skill.description %>


I read http://api.rubyonrails.org the word_wrap section and have tried all the following.

<%= word_wrap(skill.description.to_s, line_width: 8) %> #because description is stored as text in database


and

<%= word_wrap(skill.description, line_width: 8) %>


the above just doesn't work at all. I binding.pry'd it and got this error:

ArgumentError: wrong number of arguments (0 for 1..2)


I've also tried adding this to my application_controller:

def wrap(s, width=78)
s.gsub(/(.{1,#{width}})(\s+|\Z)/, "\\1\n")
end


and wrapping in my view like so:

<%= wrap(skill.description.to_s, 8) %>


I even tried putting the wrap method inside my users_controller and as a last attempt even inside my view file. Any suggestions?

I noticed it works in my console though:

wrap(skill.description, 8)
=> "code\nstuff,\nlearn\nprogramming\nin many\ndifferent\nlanguages\nright in\nyour\nbrowser\nfor free\n"

Answer Source

I figured out a hacky way to do it, please give a better solution if one is available.

(This should be able to go in the model, but its not working so I put it in the view until someone can help me with that)

def wrap(s, width=78)
  s.gsub(/(.{1,#{width}})(\s+|\Z)/, "\\1<br>").html_safe
end

Here's the view:

<%= wrap(skill.description.to_s, 65) %>

Note in the Regex I changed the \n to a
which is sort of like a newline equivalent in an html page, then I made html work by adding the .html_safe. again it seems messy but it works.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download