Sha256: 87562dcd4fe32c1c793fb8c773ceaa4ff12122e01edcd18d0a205ccd5da2daf3

Contents?: true

Size: 1.4 KB

Versions: 1

Compression:

Stored size: 1.4 KB

Contents

require 'open-uri'
require 'timeout'

class Comcetera
  attr_accessor :operator_code, :msisdn
  attr_accessor :error_code, :debug

  def initialize(attributes={})
    attributes.each do |key, value|
      self.send("#{key}=", value)
    end
  end

  class << self
    attr_accessor :username, :password, :timeout, :retries

    def timeout
      @timeout ||= 2
    end

    def retries
      @retries ||= 2
    end
    
    def password
      @password || raise("No password set for Comcetera")
    end

    def username
      @username || raise("No username set for Comcetera")
    end

    # Attempt an operator lookup based on msisdn.
    def detect(msisdn)
      attempts = 0
      while attempts <= self.retries
        attempts += 1
        begin
          Timeout::timeout(self.timeout) do
            body=open("http://api.comcetera.com/npl?user=#{self.username}&pass=#{self.password}&msisdn=#{msisdn}").read
            msisdn, operator_code = body.split("\n")[1].split(" ") # 2nd line, last word is the operator hexcode
            unless operator_code.to_s =~ /ERR\d+/
              return new(:operator_code => operator_code, :msisdn => msisdn)
            else
              return new(:operator_code => nil, :msisdn => msisdn, :error_code=>operator_code, :debug=>body)
            end
          end
        rescue Timeout::Error, SystemCallError => e
          # ignore
        end
      end
      nil
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
comcetera-0.2.0 lib/comcetera.rb