Skip to content
Browse files

Merge pull request #4554 from rodrigoflores/master

Added the :format option to number_to_percentage
  • Loading branch information...
2 parents 3e6e57e + c0a3fe3 commit c08ea0ac8e5d47068f95b395ea7704d967efbd3b @josevalim josevalim committed Jan 20, 2012
View
11 actionpack/lib/action_view/helpers/number_helper.rb
@@ -169,6 +169,8 @@ def number_to_currency(number, options = {})
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to "").
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator
# (defaults to +false+).
+ # * <tt>:format</tt> - Specifies the format of the percentage string
+ # The number field is <tt>%n</tt> (defaults to "%n%").
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid.
#
# ==== Examples
@@ -180,6 +182,7 @@ def number_to_currency(number, options = {})
# number_to_percentage(302.24398923423, :precision => 5) # => 302.24399%
# number_to_percentage(1000, :locale => :fr) # => 1 000,000%
# number_to_percentage("98a") # => 98a%
+ # number_to_percentage(100, :format => "%n %") # => 100 %
#
# number_to_percentage("98a", :raise => true) # => InvalidNumberError
def number_to_percentage(number, options = {})
@@ -193,13 +196,17 @@ def number_to_percentage(number, options = {})
options = options.reverse_merge(defaults)
+ format = options[:format] || "%n%"
+
begin
- "#{number_with_precision(number, options.merge(:raise => true))}%".html_safe
+ value = number_with_precision(number, options.merge(:raise => true))
+ format.gsub(/%n/, value).html_safe
rescue InvalidNumberError => e
if options[:raise]
raise
else
- e.number.to_s.html_safe? ? "#{e.number}%".html_safe : "#{e.number}%"
+ formatted_number = e.number.to_s.html_safe? ? format.gsub(/%n/, e.number).html_safe : format.gsub(/%n/, e.number)
+ formatted_number.html_safe? ? formatted_number.html_safe : formatted_number
end
end
end
View
1 actionpack/lib/action_view/locale/en.yml
@@ -37,6 +37,7 @@
# precision:
# significant: false
# strip_insignificant_zeros: false
+ format: "%n%"
# Used in number_to_precision()
precision:
View
1 actionpack/test/template/number_helper_test.rb
@@ -57,6 +57,7 @@ def test_number_to_percentage
assert_equal("1000.000%", number_to_percentage("1000"))
assert_equal("123.4%", number_to_percentage(123.400, :precision => 3, :strip_insignificant_zeros => true))
assert_equal("1.000,000%", number_to_percentage(1000, :delimiter => '.', :separator => ','))
+ assert_equal("1000.000 %", number_to_percentage(1000, :format => "%n %"))
end
def test_number_with_delimiter

0 comments on commit c08ea0a

Please sign in to comment.
Something went wrong with that request. Please try again.