I have the user submit a single line (“description”) that must have one number in it.
Currently I have the user submit the number at the beginning of the description “253 foo foo bar bar” — but I want to change it so that the number can be anywhere.
“foo foo foo 253 bar bar bar”, “253 foo foo bar bar”, “bar bar foo 253”
The number has a different CSS class. My goal is display the description string and wrap tags around the number. How should I structure my models / views, using Javascript / rails, in order to do this?
Here are possibilities I’ve thought of. I want to preserve MVC and also maximize performance in rendering views. The user is submitting one line that gets processed in the back end. At the moment, my database has Item.description and Item.number
-
Item.description_before,Item.number,Item.description_after— When the user submits, split the description string into two parts. This seems like it’ll have good performance and readability because in the view, I can just do<%= Item.description_before + "#{Item.number}" + Item.description_after. But then it also seems strange splitting the description into two parts. -
Item.number_position– Record the position of the number in the string and then use ruby string manipulation to add<class>tags around thenth character in the string. -
Use Javascript to find the number – But then if I’m listing 25 posts, I’d have to call this function 25 times each time the page loads and do string manipulation that way, which seems problematic.
But I’m definitely looking for new suggestions because I’m not an expert at this by any means! Or if you would have done one of the above options, any answers would be helpful as well. Thanks!
A view helper which does a regex substition would be fine and fast enough. Something like: