Class: CallerId::ReversePhoneLookup

Inherits:
Object
  • Object
show all
Defined in:
lib/caller_id.rb

Overview

This class leverages the OpenCNAM service to lookup names from phone numbers. docs.opencnam.com/guide.html

Instance Method Summary collapse

Constructor Details

#initialize(number, user = nil, key = nil) ⇒ ReversePhoneLookup

Returns a new instance of ReversePhoneLookup.



9
10
11
12
13
14
15
16
17
# File 'lib/caller_id.rb', line 9

def initialize number, user = nil, key = nil
  @phone_number = number.to_s.gsub(/\D/,'').gsub(/\A1/,'') # strip spaces, punctuation, and leading 1s.
  # TODO: consider raising a specific Exception here.
  raise "invalid format" if @phone_number.nil? || @phone_number.strip.empty? || @phone_number.length != 10
  if user && key
    @api_user = user
    @api_key  = key
  end
end

Instance Method Details

#lookupObject



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/caller_id.rb', line 19

def lookup
  begin
    response = open(get_url)
  rescue OpenURI::HTTPError
    return {:not_found => true}
  end
  return {:retry => true, :now => Time.now} if response.status[0] == "202"
  return if response.status[0] != "200"
  json_response = response.read
  results = JSON.parse(json_response)
  {:cnam => results["cnam"].strip, :number => results["number"]}
end