Phonelib

repository·master·Indexed 22 days ago

https://github.com/daddyz/phonelib

A Ruby gem for phone number validation and formatting based on Google's libphonenumber library. It provides capabilities for basic validation, E164 and national formatting, and detailed metadata retrieval including carrier, timezone, and geographic names. Includes a built-in validator for ActiveRecord and ActiveModel, support for custom regex patterns, and configurable global settings for parsing and sanitization.

Tokens
7.6K
Snippets
32
Records
38
Agent score
78%

What's inside phonelib

  1. Handle incorrect parsing or validation with custom regexes

    master
    If a phone number is being incorrectly parsed or validated, it may be due to the underlying Google libphonenumber data. If you cannot wait for an upstream fix, you can extend the validation logic using Phonelib.add_additional_regex to add specific patterns, or inspect existing custom patterns via Phonelib.additional_regexes.
  2. Use Phonelib with ActiveRecord

    master

    Phonelib provides a validator for ActiveRecord models.

    Basic Validation

    validates :attribute, phone: true

    Note: Passing a blank value will fail validation.

    Advanced Validation Options

    validates :attribute, phone: {
      possible: true,           # Check if number is a possible phone number (less strict)
      allow_blank: true,       # Validation passes if value is blank
      types: [:voip, :mobile],  # Validate against specific patterns
      countries: [:us, :ca],   # Validate against specific countries
      country_specifier: -> phone { phone.country.try(:upcase) }, # Dynamic country detection
      extensions: false          # Check for phone extension to be blank
    }
    validates :attribute, phone: { possible: true, allow_blank: true, types: [:voip, :mobile], country_specifier: -> phone { phone.country.try(:upcase) } }
  3. Configure Phonelib global settings

    master

    You can configure global behavior in a Rails initializer (e.g., config/initializers/phonelib.rb).

    Default Countries

    Set the default country or multiple default countries for parsing using ISO 3166-1 Alpha-2 codes.

    Phonelib.default_country = "CN"
    Phonelib.default_country = ['CN', 'FR']

    Parsing and Sanitization

    • Special Numbers: Enable parsing for Short Codes, Emergency, etc. (disabled by default). Phonelib.parse_special = true
    • Vanity Conversion: Convert characters to numeric representation (e.g., 800-CALL-NOW to 800-225-5669). Phonelib.vanity_conversion = true
    • Strict Check: Disable sanitization (keeping only digits). Phonelib.strict_check = true
    • Ignore Plus: Disable country reset during parsing if a number starts with + but the prefix doesn't match the specified country. Phonelib.ignore_plus = true
    • Strict Double Prefix: Disable sanitizing of double prefixes. Phonelib.strict_double_prefix_check = true
    • Custom Sanitization Regex: Define which symbols are allowed; others will cause parsing to fail. Phonelib.sanitize_regex = '[\.\-\(\) \;\+]'

    Formatting and Extensions

    • Extension Separator (Formatting): Change the separator used when formatting (default is ;). Phonelib.extension_separator = ';'
    • Extension Separators (Parsing): Define symbols used to separate extensions during parsing. Accepts a single symbol string or an array of strings. Phonelib.extension_separate_symbols = '#;' Phonelib.extension_separate_symbols = %w(ext # ; extension)

    Data Overrides and Custom Regex

    Phonelib.default_country = "CN"
    Phonelib.parse_special = true
    Phonelib.vanity_conversion = true
    Phonelib.strict_check = true
    Phonelib.ignore_plus = true
    Phonelib.sanitize_regex = '[\.\-\(\) \;\+]'
    Phonelib.strict_double_prefix_check = true
    Phonelib.extension_separator = ';'
    Phonelib.extension_separate_symbols = '#;'
    Phonelib.override_phone_data = '/path/to/override_phone_data.dat'
  4. Access formatting methods via dynamic prefixes

    master

    The PhoneFormatter module supports dynamic method calls using prefixes. You can call methods that start with international_, full_international_, e164_, or full_e164_ followed by a suffix to access specific variations.

    Note: This is implemented via method_missing and effectively maps to the core formatting methods.

    # This is handled via method_missing
    # Example: calling a method with a prefix
    # (Actual implementation details depend on how the suffix is parsed)
  5. Understand the Rails directory structure

    master

    A standard Rails application follows a specific directory layout:

    • app/: Contains application-specific code.
      • app/assets/: Images, stylesheets, and JavaScript.
      • app/controllers/: Controllers (e.g., weblogs_controller.rb).
      • app/models/: Models (e.g., post.rb).
      • app/views/: Template files (e.g., weblogs/index.html.erb).
      • app/views/layouts/: Layout templates (e.g., default.html.erb).
      • app/helpers/: View helpers.
    • config/: Configuration for environments, routing, and databases.
    • db/: Database schema (schema.rb) and migrations (db/migrate).
    • lib/: Custom application libraries (included in the load path).
    • log/: Application log files.
    • public/: Web server accessible directory (the DOCUMENT_ROOT).
    • test/: Unit, functional, and integration tests.
    • vendor/: External libraries and plugins.
  6. Debug Rails applications using logs and the logger

    master

    You can debug your application by monitoring log files or by injecting custom log messages into your code.

    Monitoring Logs

    Use the tail -f command to watch server.log and development.log in real-time. Rails automatically outputs debugging and runtime information to these files.

    Using the Ruby Logger

    You can log custom messages directly from your controllers using the Ruby logger class.

    class WeblogController < ActionController::Base
        def destroy
          @weblog = Weblog.find(params[:id])
          @weblog.destroy
          logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
        end
    end
  7. Eagerly load Phonelib data

    master

    By default, Phonelib loads data lazily on first use. In production environments, you can call eager_load! to load all phone and extended data into memory during application startup to avoid latency on the first request.

    Phonelib.eager_load!
  8. Get started with a new Rails application

    master

    To create and run a new Ruby on Rails application, follow these steps at your command prompt:

    1. Create the application: rails new myapp (replace myapp with your desired name).
    2. Navigate to the directory and start the server: cd myapp; rails server.
    3. Access the application at http://localhost:3000/.
    rails new myapp
    cd myapp
    rails server
  9. Dynamically specify country for validation

    master

    If your model stores a country code in a separate attribute, you can use the country_specifier option to tell the PhoneValidator which method to call on the record to retrieve the country context for parsing.

    class Phone < ActiveRecord::Base
      # If the record has a method `user_country` that returns a country code
      validates :number, phone: { country_specifier: :user_country }
    
      # Or using a Proc for more complex logic
      validates :number, phone: { country_specifier: ->(record) { record.determine_country_logic } }
    end
  10. Integrate Phonelib with Rails

    master
    Phonelib includes a Railtie for automatic integration with Ruby on Rails. When used in a Rails environment, it automatically adds Phonelib to the eager_load_namespaces configuration to ensure all library components are loaded correctly during the application boot process.