lib/phonelib/core.rb in phonelib-0.2.8 vs lib/phonelib/core.rb in phonelib-0.2.9

- old
+ new

@@ -96,21 +96,23 @@ fixed_or_mobile: 'Fixed Line or Mobile' } # method for parsing phone number. # On first run fills @@phone_data with data present in yaml file - def parse(phone, passed_country = nil) + def parse(original, passed_country = nil) load_data + sanitized = sanitize_phone original country = country_or_default_country(passed_country) - if phone.nil? || country.nil? + if sanitized.empty? # has to return instance of Phonelib::Phone even if no phone passed - Phonelib::Phone.new(phone, @@phone_data) + Phonelib::Phone.new(sanitized, original, @@phone_data) else - detected = detect_and_parse_by_country(phone, country) + detected = detect_or_parse_by_country(sanitized, original, country) if passed_country.nil? && @@default_country && detected.invalid? - Phonelib::Phone.new(phone, @@phone_data) + # try to detect country for number if it's invalid for specified one + detect_or_parse_by_country(sanitized, original) else detected end end end @@ -158,15 +160,23 @@ country = country || @@default_country country.to_s.upcase unless country.nil? end # Get Phone instance for provided phone with country specified - def detect_and_parse_by_country(phone, country) - detected = @@phone_data.find { |data| data[:id] == country } - if detected - phone = convert_phone_to_e164(phone, detected) - Phonelib::Phone.new(phone, [detected]) + def detect_or_parse_by_country(phone, original, country = nil) + if country.nil? + Phonelib::Phone.new(phone, original, @@phone_data) + else + detected = @@phone_data.find { |data| data[:id] == country } + if detected + phone = convert_phone_to_e164(phone, detected) + if phone[0] == '+' + detect_or_parse_by_country(phone[1..-1], original) + else + Phonelib::Phone.new(phone, original, [detected]) + end + end end end # Create phone representation in e164 format def convert_phone_to_e164(phone, data) #prefix, national_prefix) @@ -174,15 +184,20 @@ rx << "(#{data[Core::INTERNATIONAL_PREFIX]})?" rx << "(#{data[Core::COUNTRY_CODE]})?" rx << "(#{data[Core::NATIONAL_PREFIX]})?" rx << "(#{data[Core::TYPES][Core::GENERAL][Core::VALID_PATTERN]})" - match = phone.gsub('+', '').match(/^#{rx.join}$/) + match = phone.match(/^#{rx.join}$/) if match - national_start = 1.upto(3).map {|i| match[i].to_s.length}.inject(:+) + national_start = (1..3).map { |i| match[i].to_s.length }.inject(:+) "#{data[Core::COUNTRY_CODE]}#{phone[national_start..-1]}" else - phone + phone.sub(/^#{data[Core::INTERNATIONAL_PREFIX]}/, '+') end + end + + # Sanitizes passed phone number. Returns only digits from passed string. + def sanitize_phone(phone) + phone && phone.gsub(/[^0-9]+/, '') || '' end end end