skwpspace yan pritzker’s home on the web

skwpspace is Yan Pritzker's home on the web

Blog :: Photography :: About Me

hello, i'm yan

This blog is about startups, blogging, Ruby On Rails, virtualization and cloud computing, photography, customer service, marketing, ux and design, git, and lots more.

Get updates by email
Follow me on twitter

Top Posts

planypus

I'm the founder of Planypus, the place to share your plans!

cohesiveft

Accessible, manageable, virtualized application stacks ready to download or deploy to the cloud!

flickr

at the paradeat the parade@slava626@leorazellman and @smazo at bat17my poor ricohyou're wearing my sweaterthe graduatethe answer, my friend

Archives

Contact

Reach me at yan at pritzker.ws

Posted
13 May 2008 @ 10pm

Tagged
code, html, ruby, thoughts

Ruby/html trick: wrap long strings with invisible wordwrap characters

def wrap_long_string(text,max_width = 20)
  (text.length < max_width) ?
    text :
    text.scan(/.{1,#{max_width}}/).join(<wbr>)
end

3 Comments

Posted by
Michele
21 May 2008 @ 9pm

Hi Yan,

I stumbled upon this post while looking for a good way to do word wrapping.

Your method looks good, except it could break words inside tags. You might want to check this one out instead: it makes sure not to break words inside and in pre blocks.

I’d thought about tokenizing and making sure to wrap only words between tags, but in the end it was too much overhead for such a simple task, and I guess the above is good enough (actually, it’s perfect if are correctly escaped when not used to surround tags).

I hope this helps. :)


Posted by
yan
21 May 2008 @ 9pm

Thanks for the heads up, I also realized there was a bug in my code that would swallow spaces in the string. I fixed the regex not to do that. The link you showed, I found that after I wrote my post. In my case, I actually didn’t care as much about breaking tags because I had only pure strings without tags to deal with. Probably the other implementation is more complete but also, I would guess, slightly slower. Thanks for the link though!


Posted by
Michele
21 May 2008 @ 9pm

I agree, it’s definitely slower, but well worth it if you have to deal with text containing tags.


Leave a Comment

Git tips & tricks part 4: more on cherry picking Rails tagging plugins overview and comparison