lib/phonelib/phone_analyzer.rb in phonelib-0.6.5 vs lib/phonelib/phone_analyzer.rb in phonelib-0.6.6
- old
+ new
@@ -16,31 +16,51 @@
# * +passed_country+ - Country provided for parsing. Must be ISO code of
# country (2 letters) like 'US', 'us' or :us for United States
def analyze(phone, passed_country)
country = country_or_default_country passed_country
- result = try_to_parse_single_country(phone, country)
- # if previous parsing failed, trying for all countries
- if passed_country.nil? && \
- (result.nil? || result.empty? || result.values.first[:valid].empty?)
-
- detected = detect_and_parse phone
- result = detected.empty? ? result || {} : detected
- end
- result || {}
+ result = try_to_parse_country(phone, country)
+ d_result = case
+ when result && result.values.find {|e| e[:valid].any? }
+ # all is good, return result
+ when passed_country.nil?
+ # trying for all countries if no country was passed
+ detect_and_parse phone
+ when !original_string.start_with?('+') && country_can_double_prefix?(country)
+ # if country allows double prefix trying modified phone
+ try_to_parse_country(changed_double_prefixed_phone(country, phone), country)
+ end
+ better_result(result, d_result)
end
private
+ # method checks which result is better to return
+ def better_result(base_result, result = nil)
+ if result.nil?
+ return base_result || {}
+ end
+
+ if base_result.nil? || base_result.empty? || base_result.values.find {|e| e[:possible].any? }.nil?
+ return result
+ end
+
+ if result && result.values.find {|e| e[:valid].any? }
+ return result
+ end
+
+ base_result || {}
+ end
+
# trying to parse phone for single country including international prefix
# check for provided country
#
# ==== Attributes
#
# * +phone+ - phone for parsing
# * +country+ - country to parse phone with
- def try_to_parse_single_country(phone, country)
+ def try_to_parse_country(phone, country)
data = Phonelib.phone_data[country]
return nil unless country && data
# if country was provided and it's a valid country, trying to
# create e164 representation of phone number,
@@ -77,11 +97,11 @@
# * +phone+ - phone number for parsing
def detect_and_parse(phone)
result = {}
Phonelib.phone_data.each do |key, data|
parsed = parse_single_country(phone, data)
- if allows_double_prefix(data, phone, parsed && parsed[key])
- parsed = parse_single_country("#{data[:country_code]}#{phone}", data)
+ if double_prefix_allowed?(data, phone, parsed && parsed[key])
+ parsed = parse_single_country(changed_double_prefixed_phone(key, phone), data)
end
result.merge!(parsed) unless parsed.nil?
end
result
end