Skip to content

Commit 78564a0

Browse files
committed
fixed bug for when no address is found, added test. Also added docs.
1 parent 3160d69 commit 78564a0

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

README.textile

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ Find and/or replace mailing addresses in strings.
55
h2. Examples
66

77
<pre><code>
8+
require 'rubygems'
9+
require 'address_extractor'
10+
811
string = <<EOF
912
Please send the package to 123 Foo St., Someplace FL
1013

lib/address_extractor.rb

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,43 @@
11
class AddressExtractor
22
class << self
33

4+
# Returns hash for address if address found.
5+
# Returns nil if no address found.
46
def first_address(string)
57
hashify_results string.scan(ADDRESS_PATTERN).first
68
end
7-
9+
10+
# Returns array of hashes for each address found.
11+
# Returns empty array if no addresses found.
812
def find_addresses(string)
913
string.scan(ADDRESS_PATTERN).collect { |a| hashify_results(a) }.compact
1014
end
1115

16+
# Pass it a block that recieves 2 parameters:
17+
# address hash
18+
# matched address string ($&)
19+
# Whatever your block returns will be used for the substition.
20+
# Returns new string with substition applied to first identified address.
21+
# If no address found, returns same string unaltered.
1222
def replace_first_address(string)
1323
hash = first_address(string)
1424
string.sub(ADDRESS_PATTERN) do |match|
1525
yield(hash, $&)
1626
end
1727
end
18-
28+
29+
# Same as +replace_first_address+ but applies substition to all identified addresses.
1930
def replace_addresses(string)
2031
string.gsub(ADDRESS_PATTERN) do |match|
2132
hash = hashify_results match.scan(ADDRESS_PATTERN).first
2233
useful_address?(hash) ? yield(hash, $&) : match
2334
end
2435
end
2536

37+
private
38+
2639
def hashify_results(matches)
40+
return nil if matches.nil?
2741
result = { }
2842
capture_index = 0
2943
CAPTURE_MAP.each do |field|

test/test_address_extractor.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,13 @@ def test_replace_addresses
3333
assert string =~ /via mail at:\n skidoosh/
3434
end
3535

36+
def test_no_addresses_found
37+
assert_nil AddressExtractor.first_address("foo")
38+
assert_equal [], AddressExtractor.find_addresses("foo")
39+
assert_equal "foo", AddressExtractor.replace_first_address("foo")
40+
assert_equal "foo", AddressExtractor.replace_addresses("foo")
41+
end
42+
3643
module Helpers
3744
def assert_first_address(a)
3845
assert_not_nil a

0 commit comments

Comments
 (0)