Sha256: b1250677038794ab63b0090a7bf270c5016d9ef0b22b929651c071bac181d606

Contents?: true

Size: 1.13 KB

Versions: 1

Compression:

Stored size: 1.13 KB

Contents

require 'ruphone/version'

module Ruphone
  # Normalize russian phone numbers to +7XXXXXXXXXX format. Examples:
  #
  #   Ruphone.normalize('8921-746-95-48')
  #   # => "+79217469548"
  #
  #   Ruphone.normalize('8(921) 746-95-48')
  #   # => "+79217469548"
  #
  #   Ruphone.normalize('746-95-48', city_code: '+7843')
  #   # => "+78437469548"
  #
  def self.normalize(phone, args = {})
    return phone if phone.nil?

    phone = phone.tr('^0-9', '')
    return phone if phone.size.zero?

    return prefix(phone) if phone.size == 10

    if phone.size == 11
      return plus(phone) if phone.start_with?('7')
      return prefix(phone[1..-1]) if phone.start_with?('8')
    end

    city_code = normalize_city_code(args[:city_code])
    if city_code && phone.size == 11 - city_code.size
      return plus("#{city_code}#{phone}")
    end

    phone
  end

  class << self
    private

    def prefix(phone)
      "+7#{phone}"
    end

    def plus(phone)
      "+#{phone}"
    end

    def normalize_city_code(city_code)
      return city_code if city_code.nil?
      return city_code[1..-1] if city_code.start_with?('+')
      city_code
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ruphone-0.0.2 lib/ruphone.rb