diff options
author | Pan GaoYong <pan.gaoyong@gmail.com> | 2016-04-02 19:33:33 +0800 |
---|---|---|
committer | Pan GaoYong <pan.gaoyong@gmail.com> | 2016-04-02 20:13:22 +0800 |
commit | 4e977da541307dd650917b49e9410a3ca753a944 (patch) | |
tree | 9c6c076bcc8fc3cefdad57dce5f4e0fb037d94dd /activesupport/lib/active_support/number_helper | |
parent | 442207387e626d69154f942651c5fbd8d573f2c6 (diff) | |
download | rails-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')
-rw-r--r-- | activesupport/lib/active_support/number_helper/number_to_phone_converter.rb | 13 |
1 files changed, 11 insertions, 2 deletions
diff --git a/activesupport/lib/active_support/number_helper/number_to_phone_converter.rb b/activesupport/lib/active_support/number_helper/number_to_phone_converter.rb index af2ee56d91..dee74fa7a6 100644 --- a/activesupport/lib/active_support/number_helper/number_to_phone_converter.rb +++ b/activesupport/lib/active_support/number_helper/number_to_phone_converter.rb @@ -18,12 +18,16 @@ module ActiveSupport end def convert_with_area_code(number) - number.gsub!(/(\d{1,3})(\d{3})(\d{4}$)/,"(\\1) \\2#{delimiter}\\3") + default_pattern = /(\d{1,3})(\d{3})(\d{4}$)/ + number.gsub!(regexp_pattern(default_pattern), + "(\\1) \\2#{delimiter}\\3") number end def convert_without_area_code(number) - number.gsub!(/(\d{0,3})(\d{3})(\d{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3") + default_pattern = /(\d{0,3})(\d{3})(\d{4})$/ + number.gsub!(regexp_pattern(default_pattern), + "\\1#{delimiter}\\2#{delimiter}\\3") number.slice!(0, 1) if start_with_delimiter?(number) number end @@ -43,6 +47,11 @@ module ActiveSupport def phone_ext(ext) ext.blank? ? "" : " x #{ext}" end + + def regexp_pattern(default_pattern) + opts.fetch :pattern, default_pattern + end + end end end |