lib/phonelib/core.rb in phonelib-0.2.6 vs lib/phonelib/core.rb in phonelib-0.2.7

- old
+ new

@@ -94,13 +94,10 @@ fixed_line: 'Fixed Line', mobile: 'Mobile', fixed_or_mobile: 'Fixed Line or Mobile' } - # array of types not included for validation check in cycle - NOT_FOR_CHECK = [:general_desc, :fixed_line, :mobile, :fixed_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) load_data @@ -150,13 +147,12 @@ private # Load data file into memory def load_data - require 'yaml' - data_file = File.dirname(__FILE__) + '/../../data/phone_data.yml' - @@phone_data ||= YAML.load_file(data_file) + data_file = File.dirname(__FILE__) + '/../../data/phone_data.dat' + @@phone_data ||= Marshal.load(File.read(data_file)) end # Get country that was provided or default country in needable format def country_or_default_country(country) country = country || @@default_country @@ -165,22 +161,28 @@ # 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[Core::COUNTRY_CODE], - detected[Core::NATIONAL_PREFIX]) + phone = convert_phone_to_e164(phone, detected) + Phonelib::Phone.new(phone, [detected]) end - Phonelib::Phone.new(phone, [detected]) end # Create phone representation in e164 format - def convert_phone_to_e164(phone, prefix, national_prefix) - return phone if phone.gsub('+', '').start_with?(prefix) - if !!national_prefix && phone.start_with?(national_prefix) - phone = phone[1..phone.length] + def convert_phone_to_e164(phone, data) #prefix, national_prefix) + rx = [] + 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}$/) + if match + national_start = 1.upto(3).map {|i| match[i].to_s.length}.inject(:+) + "#{data[Core::COUNTRY_CODE]}#{phone[national_start..-1]}" + else + phone end - prefix + phone end end end