Created
April 28, 2009 19:13
-
-
Save samg/103323 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# == a smarter way to pluralize | |
# | |
# Accepts an integer as an optional argument | |
# >> "actress".smart_pluralize | |
# => "actresses" | |
# >> "guitar".smart_pluralize(1) | |
# => "guitar" | |
# >> "monkey".smart_pluralize(2) | |
# => "monkeys" | |
# | |
# Understands quantity strings | |
# >> "1 monkey".smart_pluralize | |
# => "1 monkey" | |
# >> "900 monkey".smart_pluralize | |
# => "900 monkeys" | |
class String | |
def smart_pluralize num=self | |
num.to_i.abs == 1 ? self : pluralize | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'activesupport' | |
require File.join(File.dirname(__FILE__), 'smart_pluralize') | |
require 'spec' | |
describe String do | |
it "should respond to smart_pluralize" do | |
"".respond_to?(:smart_pluralize).should be_true | |
end | |
describe "with one integer argument" do | |
it "should not pluralize with arg of 1" do | |
"monkey".smart_pluralize(1).should == "monkey" | |
end | |
it "should not pluralize with arg of -1" do | |
"monkey".smart_pluralize(-1).should == "monkey" | |
end | |
it "should pluralize with arg of 0" do | |
"monkey".smart_pluralize(0).should == "monkeys" | |
end | |
it "should pluralize with arg of 2..100" do | |
(2..100).each do |i| | |
"monkey".smart_pluralize(i).should == "monkeys" | |
end | |
end | |
it "should pluralize with arg of -100..-2" do | |
(-100..-2).each do |i| | |
"monkey".smart_pluralize(i).should == "monkeys" | |
end | |
end | |
end | |
describe "with no args" do | |
it "should pluralize with no args" do | |
"monkey".smart_pluralize.should == "monkeys" | |
end | |
it "should not pluralize 1 monkey" do | |
"1 monkey".smart_pluralize.should == "1 monkey" | |
end | |
it "should not pluralize -1 monkey" do | |
"-1 monkey".smart_pluralize.should == "-1 monkey" | |
end | |
it "should pluralize 0 monkey" do | |
"0 monkey".smart_pluralize.should == "0 monkeys" | |
end | |
it "should pluralize 2 - 100 monkeys" do | |
(2..100).each do |i| | |
"#{i} monkey".smart_pluralize.should == "#{i} monkeys" | |
end | |
end | |
it "should pluralize -100 through -2 monkeys" do | |
(-100..-2).each do |i| | |
"#{i} monkey".smart_pluralize.should == "#{i} monkeys" | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment