Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails is/are pluralisation

Is there a helper to avoid this sort of code?

= @leads.length == 1 ? 'is' : 'are'

I know about pluralize but it doesn't help in this case. I know that writing a helper would be trivial, I want to know if there's something in the Rails API that I have overlooked.

Thanks,

-Tim

like image 229
Tim Harding Avatar asked Nov 06 '09 08:11

Tim Harding


3 Answers

As t6d said you need to add is/are to the Rails inflector. Just the code from td6, but you need to add the ActiveSupport namespace:

ActiveSupport::Inflector.inflections do |inflection|
  inflection.irregular "is", "are"
end

Now the helper Rails has built in is pluralize, but in a view that won't do what you want. For example:

pluralize(@leads.length,'is')

outputs (for 2 leads)

2 are

For what you want you need to make your own helper that will pluralize the word, but not output the count. So if you base it on the current rails pluralize:

def pluralize_no_count(count, singular, plural = nil)
  ((count == 1 || count == '1') ? singular : (plural || singular.pluralize))
end
like image 168
scottd Avatar answered Oct 27 '22 23:10

scottd


In conclusion I'll go for:

Config

# inflections.rb
Inflector.inflections do |inflection|
  inflection.irregular "is", "are"
  inflection.irregular "has", "have"
end

Rails 3

"#{subject} #{'is'.pluralize(count)} working!"

Rails 2

# application_helper.rb
def signularize_or_pluralize(word, count)
  if count.to_i == 1
    word.singularize
  else
    word.pluralize
  end
end

# in the view view
"#{subject} #{signularize_or_pluralize('is', count)} working!"
like image 20
ecoologic Avatar answered Oct 27 '22 22:10

ecoologic


Maybe you could use pluralize and add a inflection for 'is'

Inflector.inflections do |inflection|
  inflection.irregular "is", "are"
end

so that

'is'.pluralize # => 'are'

(I didn't test the solution, but it should work.)

like image 39
t6d Avatar answered Oct 28 '22 00:10

t6d