Skip to content

Commit

Permalink
Add String#ascii_only.
Browse files Browse the repository at this point in the history
  • Loading branch information
trans committed Jan 26, 2014
1 parent 966c5a9 commit 693ef4c
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
52 changes: 52 additions & 0 deletions lib/core/facets/string/ascii_only.rb
@@ -0,0 +1,52 @@
class String
# Get a new string with non-ASCII characters removed.
#
# alt - String to replace non-ASCII characters with.
# Defaults to a blank string (`''`).
#
# Examples
#
# 'abc'.ascii_only #=> 'abc'
# '中文123'.ascii_only #=> '123'
#
# Returns a copy of [String] with ASCII characters only.
#
# CREDIT: Nathan Long
#
# SEE: http://stackoverflow.com/questions/1268289
def ascii_only(alt='')
encoding_options = {
:invalid => :replace, # Replace invalid byte sequences
:undef => :replace, # Replace anything not defined in ASCII
:replace => alt, # Use a blank for those replacements
:UNIVERSAL_NEWLINE_DECORATOR => true # Always break lines with \n
}
self.encode(Encoding.find('ASCII'), encoding_options)
end

# Modify string keeping only ASCII characters.
#
# alt - String to replace non-ASCII characters with.
# Defaults to a blank string (`''`).
#
# Examples
#
# 'abc'.ascii_only! #=> 'abc'
# '中文123'.ascii_only! #=> '123'
#
# Returns [String]
#
# CREDIT: Nathan Long
#
# SEE: http://stackoverflow.com/questions/1268289
def ascii_only!(alt='')
encoding_options = {
:invalid => :replace, # Replace invalid byte sequences
:undef => :replace, # Replace anything not defined in ASCII
:replace => alt, # Use a blank for those replacements
:UNIVERSAL_NEWLINE_DECORATOR => true # Always break lines with \n
}
self.encode!(Encoding.find('ASCII'), encoding_options)
end

end
30 changes: 30 additions & 0 deletions test/core/string/test_ascii_only.rb
@@ -0,0 +1,30 @@
covers 'facets/string/ascii_only'

test_case String do

method :ascii_only do
test 'without any non-ascii' do
'abc'.ascii_only.assert == 'abc'
end

test 'with non-ascii' do
'中文123'.ascii_only.assert == '123'
end
end

method :ascii_only! do
test 'without any non-ascii' do
s = 'abc'
s.ascii_only!
s.assert == 'abc'
end

test 'with non-ascii' do
s = '中文123'
s.ascii_only!
s.assert == '123'
end
end

end

0 comments on commit 693ef4c

Please sign in to comment.