Skip to content

Instantly share code, notes, and snippets.

@lachlanhardy
Created September 26, 2010 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lachlanhardy/597754 to your computer and use it in GitHub Desktop.
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
@carlwoodward
Copy link

This is how I would do it but I'm not sure of your setup...


= number
%span{:class => 'thing'}= number == 1 ? 'thing' : 'thing'.pluralize

But I'm pretty lazy.

@lachlanhardy
Copy link
Author

Yeah, cool, thanks!

@stephan-buckmaster
Copy link

You sure there are no " characters in your text?

@carlwoodward
Copy link

Are you asking why I didn't use them?

@stephan-buckmaster
Copy link

Sorry, what I meant is if text='abc"def' then

class="#{class_name}"> will become

class="abc"def"> which is asking for trouble

@carlwoodward
Copy link

That is true.

Although I don't this that it is a common use case that you need to trap. But up to you.

@lachlanhardy
Copy link
Author

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?

@stephan-buckmaster
Copy link

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.

@lachlanhardy
Copy link
Author

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)

@stephan-buckmaster
Copy link

Redundant in the sense of repetition :-)

Anyway, looks like things are working fine for you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment