0

Is there a ruby\rails way to determine string length?
(There is a example below with both a and b length equal to 10 chars but quite different actual length)

e.g.
a = lllllllllll
b = WWWWWWWWWWW

Font should also be considered

P.S.
ended up using https://github.com/tbasse/jquery-truncate on a client-side

ted
  • 5,219
  • 7
  • 36
  • 63

2 Answers2

1

The response is here

How do I calculate a String's width in Ruby?

the_text = "TheTextYouWantTheWidthOf"
label = Draw.new
label.font = "Vera" #you can also specify a file name... check the rmagick docs to be sure
label.text_antialias(true)
label.font_style=Magick::NormalStyle
label.font_weight=Magick::BoldWeight
label.gravity=Magick::CenterGravity
label.text(0,0,the_text)
metrics = label.get_type_metrics(the_text)
width = metrics.width
height = metrics.height
Community
  • 1
  • 1
pierallard
  • 3,326
  • 3
  • 21
  • 48
  • @SergioTulentsev Sure... It's more 'hack' than true answer. I prefer the method of character length approximation described in the previous link. More efficient, less hack. – pierallard Apr 17 '13 at 13:37
  • Is there a way to get the length in pixel via Font method? – user3163916 Feb 04 '14 at 22:56
1

There is absolutely no way to know how wide the string will be in pixels, from the server side. You can take a guess, by rendering the string using the same font you specify in your CSS, however the end-user can override those settings in their browser, making your guess invalid. Or, the user might not have the font you do, and the browser substitutes one from a similar family, which has different widths for certain characters; The result again is going to be different from what you thought.

The only way to know, if it's even possible, would be to use JavaScript in the user's browser, basing the calculation on what the final rendered font is, as specified by any user-CSS, then return that to your server for further processing, however that really breaks down the idea of how the web and browsers work.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303