aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/number_helper.rb
diff options
context:
space:
mode:
authorPan GaoYong <pan.gaoyong@gmail.com>2016-04-02 19:33:33 +0800
committerPan GaoYong <pan.gaoyong@gmail.com>2016-04-02 20:13:22 +0800
commit4e977da541307dd650917b49e9410a3ca753a944 (patch)
tree9c6c076bcc8fc3cefdad57dce5f4e0fb037d94dd /activesupport/lib/active_support/number_helper.rb
parent442207387e626d69154f942651c5fbd8d573f2c6 (diff)
downloadrails-4e977da541307dd650917b49e9410a3ca753a944.tar.gz
rails-4e977da541307dd650917b49e9410a3ca753a944.tar.bz2
rails-4e977da541307dd650917b49e9410a3ca753a944.zip
`number_to_phone` formats number with regexp
By default, this method formats US number. This commit extends its functionality to format number for other countries with a custom regular expression. number_to_phone(18812345678, pattern: /(\d{3})(\d{4})(\d{4})/) # => 188-1234-5678 The output phone number is divided into three groups, so the regexp should also match three groups of numbers.
Diffstat (limited to 'activesupport/lib/active_support/number_helper.rb')
-rw-r--r--activesupport/lib/active_support/number_helper.rb9
1 files changed, 8 insertions, 1 deletions
diff --git a/activesupport/lib/active_support/number_helper.rb b/activesupport/lib/active_support/number_helper.rb
index 55628f0313..7a49bbb960 100644
--- a/activesupport/lib/active_support/number_helper.rb
+++ b/activesupport/lib/active_support/number_helper.rb
@@ -15,7 +15,7 @@ module ActiveSupport
extend self
- # Formats a +number+ into a US phone number (e.g., (555)
+ # Formats a +number+ into a phone number (US by default e.g., (555)
# 123-9876). You can customize the format in the +options+ hash.
#
# ==== Options
@@ -27,6 +27,8 @@ module ActiveSupport
# end of the generated number.
# * <tt>:country_code</tt> - Sets the country code for the phone
# number.
+ # * <tt>:pattern</tt> - Specifies how the number is divided into three
+ # groups with the custom regexp to override the default format.
# ==== Examples
#
# number_to_phone(5551234) # => "555-1234"
@@ -40,6 +42,11 @@ module ActiveSupport
#
# number_to_phone(1235551234, country_code: 1, extension: 1343, delimiter: '.')
# # => "+1.123.555.1234 x 1343"
+ #
+ # number_to_phone(75561234567, pattern: /(\d{1,4})(\d{4})(\d{4})$/, area_code: true)
+ # # => "(755) 6123-4567"
+ # number_to_phone(13312345678, pattern: /(\d{3})(\d{4})(\d{4})$/))
+ # # => "133-1234-5678"
def number_to_phone(number, options = {})
NumberToPhoneConverter.convert(number, options)
end