-
-
Save lachlanhardy/597754 to your computer and use it in GitHub Desktop.
# to explain | |
# ActionView lets me write | |
# pluralize(something.length, "Thing") => | |
# "2 Things" | |
# | |
# But in this case, I want to separate the number from the text in HTML (to put an icon in between). | |
# Since I'm using CSS sprites, the easiest way is to wrap the text in a span with a class on it to get the correct image | |
# Thus: | |
def new_pluralize (number, text) | |
class_name = text.downcase | |
unless number == 1 | |
text = text.pluralize | |
end | |
"#{number} <span class=\"#{class_name}\">#{text}</span>" | |
end | |
# Which lets me call | |
# new_pluralize(something.length, "Thing") => | |
# "2 <span class="thing">Things</span>" | |
# Then all I have to do is insert it in my view without escaping the HTML |
You sure there are no " characters in your text?
Are you asking why I didn't use them?
Sorry, what I meant is if text='abc"def' then
class="#{class_name}"> will become
class="abc"def"> which is asking for trouble
That is true.
Although I don't this that it is a common use case that you need to trap. But up to you.
In my case, I am sure, because the 'text' value always comes from my templates rather than users etc, but that's a good point.
How would you escape that? Just strip it?
One possibility is to use
number.to_s + content_tag(:span, text, :class => class_name)
But I think it might be better to use some mapping; I don't know how many classes you are expecting. Are they all really going to get different markup? It looks a bit redundant to have the text both in the class, and the content of the span.
Redundant how? One is content, one is data hook...
Basically, I'm using CSS to provide an icon for each of these cases. According to the design, the icon needs to go between the number and the text (and frankly that makes heaps more sense)
Redundant in the sense of repetition :-)
Anyway, looks like things are working fine for you
Yeah, cool, thanks!