Easy to use String#scrub
. Prevent Invalid byte sequence in UTF-8.
Wrap params[:name].respond_to?(:scrub) ? params[:name].scrub : params[:name]
to params[:name].awesome_scrub
.
@name = params[:name].presence || 'nobody'
@name = awesome_scrub(params[:name]).presence || 'nobody'
Almost time this is no problem, but params[:name] include invalid byte sequence in UTF-8
, like invalid_byte_sequence.presence
(invalid_byte_sequence.present?
) raises ArgumentError: invalid byte sequence in UTF-8
.
This problem's solution is String#scrub
(Feature of Ruby2.1, and string-scrub
gem which backport for Ruby2.0), this replaces invalid characters. Feature #6752: Replacing ill-formed subsequencce - ruby-trunk - Ruby Issue Tracking System
This stil has problem for writing code, params[:name]
is String
or nil
, and some case Array
, Fixnum
, and other object does not have #scrub
method.
name = params[:name].respond_to?(:scrub) ? params[:name].scrub : params[:name]
@name = name.presence || 'nobody'
@name = awesome_scrub(params[:name]).presence || 'nobody'
# call scrub
awesome_scrub(args) #=> args.scrub
# call scrub!
awesome_scrub!(args) #=> args.scrub!
class Foo
include AwesomeScrub
def bar
awesome_scrub(any)
end
end
OR
class Foo
extend AwesomeScrub
def bar
awesome_scrub(any)
end
end
OR
AwesomeScrub::awesome_scrub(any)
Add this line to your application's Gemfile:
gem 'awesome_scrub'
And then execute:
$ bundle
Or install it yourself as:
$ gem install awesome_scrub
- Fork it ( http://github.com/sanemat/awesome_scrub/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request