Question

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"
Was it helpful?

Solution

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.

OTHER TIPS

word_wrap adds \n. Use simple format to replace \n with with html newlines :

<%= simple_format(word_wrap(skill.description, line_width: 8)) %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top