Module: MobME::Infrastructure::Utilities::CoreExtensions::MSISDN

Included in:
String
Defined in:
lib/mobme_support/core_ext/string/msisdn.rb

Overview

String extension, which allows MSISDN validation.

Instance Method Summary collapse

Instance Method Details

#msisdn(options_hash = {}) ⇒ String?

Validates and converts an MSISDN in the string to the required format.

Examples:

Convert to an international format.

"31234567".msisdn(:country => "BH", :format => 'international')
"0097331234567"

Convert to a 10 digit mobile number.

"+919846819033".msisdn(:format => 'local')
"9846819033"

Parameters:

  • options_hash (Hash) (defaults to: {})

    Options to pass into the function

Options Hash (options_hash):

  • :country (String) — default: 'IN'

    The ISO 3166 code for the MSISDN’s country.

  • :format (String) — default: 'local'

    Either ‘local’, ‘international’, ‘country’, ‘plus_country’.

Returns:

  • (String, nil)

    Validated MSISDN, or nil.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/mobme_support/core_ext/string/msisdn.rb', line 27

def msisdn(options_hash = {})
  default_options = {
    :country => 'IN',
    :format => 'local'
  }

  options_hash = options_hash.symbolize_keys.reverse_merge(default_options)

  @@msdn_format_data ||= YAML.load_file(File.dirname(__FILE__) + "/msisdn_formats.yml")
  msisdn_format = @@msdn_format_data[options_hash[:country]]

  msisdn = self.strip
  if msisdn.match(msisdn_format['regexp'])
    local_segment = msisdn[-(msisdn_format['local_digits'])..-1]
    case options_hash[:format]
      when 'local'
        local_segment
      when 'country'
        "#{msisdn_format['country_code']}#{local_segment}"
      when 'plus_country'
        "+#{msisdn_format['country_code']}#{local_segment}"
      when "international"
        "#{msisdn_format['international_prefix']}#{msisdn_format['country_code']}#{local_segment}"
    end
  else
    nil
  end
end

#msisdn?(options_hash = {}) ⇒ Boolean

Validates an MSISDN.

Examples:

Validate an Indian MSISDN.

"9846819033".msisdn?
true

Validate an non-Indian MSISDN.

"+919846819033".msisdn?(:country => 'CA')
false

Parameters:

  • options_hash (Hash) (defaults to: {})

    Options to pass into the function.

Options Hash (options_hash):

  • :country (String) — default: 'IN'

    The ISO 3166 code for the MSISDN’s country.

Returns:

  • (Boolean)

    True if string is a valid MSISDN. False, otherwise.



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/mobme_support/core_ext/string/msisdn.rb', line 67

def msisdn?(options_hash = {})
  default_options = {
      :country => 'IN',
      :format => 'local'
  }
  options_hash = options_hash.symbolize_keys.reverse_merge(default_options)
  @@msdn_format_data ||= YAML.load_file(File.dirname(__FILE__) + "/msisdn_formats.yml")
  msisdn_format = @@msdn_format_data[options_hash[:country]]
 return false unless self =~ msisdn_format['regexp']
  true
end