File tree Expand file tree Collapse file tree 3 files changed +26
-2
lines changed Expand file tree Collapse file tree 3 files changed +26
-2
lines changed Original file line number Diff line number Diff line change @@ -5,6 +5,9 @@ Find and/or replace mailing addresses in strings.
5
5
h2. Examples
6
6
7
7
<pre><code>
8
+ require 'rubygems'
9
+ require 'address_extractor'
10
+
8
11
string = <<EOF
9
12
Please send the package to 123 Foo St., Someplace FL
10
13
Original file line number Diff line number Diff line change 1
1
class AddressExtractor
2
2
class << self
3
3
4
+ # Returns hash for address if address found.
5
+ # Returns nil if no address found.
4
6
def first_address ( string )
5
7
hashify_results string . scan ( ADDRESS_PATTERN ) . first
6
8
end
7
-
9
+
10
+ # Returns array of hashes for each address found.
11
+ # Returns empty array if no addresses found.
8
12
def find_addresses ( string )
9
13
string . scan ( ADDRESS_PATTERN ) . collect { |a | hashify_results ( a ) } . compact
10
14
end
11
15
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.
12
22
def replace_first_address ( string )
13
23
hash = first_address ( string )
14
24
string . sub ( ADDRESS_PATTERN ) do |match |
15
25
yield ( hash , $&)
16
26
end
17
27
end
18
-
28
+
29
+ # Same as +replace_first_address+ but applies substition to all identified addresses.
19
30
def replace_addresses ( string )
20
31
string . gsub ( ADDRESS_PATTERN ) do |match |
21
32
hash = hashify_results match . scan ( ADDRESS_PATTERN ) . first
22
33
useful_address? ( hash ) ? yield ( hash , $&) : match
23
34
end
24
35
end
25
36
37
+ private
38
+
26
39
def hashify_results ( matches )
40
+ return nil if matches . nil?
27
41
result = { }
28
42
capture_index = 0
29
43
CAPTURE_MAP . each do |field |
Original file line number Diff line number Diff line change @@ -33,6 +33,13 @@ def test_replace_addresses
33
33
assert string =~ /via mail at:\n skidoosh/
34
34
end
35
35
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
+
36
43
module Helpers
37
44
def assert_first_address ( a )
38
45
assert_not_nil a
You can’t perform that action at this time.
0 commit comments