diff --git a/README.md b/README.md index d73cbfa..031c764 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,17 @@ class EloquentPokerPlayer < ActiveRecord::Base end ``` +### Using `regex` + +```ruby +class User < ActiveRecord::Base + # Strip off characters defined by RegEx + strip_attributes :only => [:first_name, :last_name], :regex => /[^[:alpha:]\s]/ + # Strip off non-integers + strip_attributes :only => [:phone], :regex => /[^0-9]/ +end +``` + ## Usage Patterns ### Other ORMs implementing `ActiveModel` diff --git a/lib/strip_attributes.rb b/lib/strip_attributes.rb index 3dbce6b..0ec2a9b 100644 --- a/lib/strip_attributes.rb +++ b/lib/strip_attributes.rb @@ -19,7 +19,7 @@ def strip_attributes!(options = nil) end module StripAttributes - VALID_OPTIONS = [:only, :except, :allow_empty, :collapse_spaces] + VALID_OPTIONS = [:only, :except, :allow_empty, :collapse_spaces, :regex] # Necessary because Rails has removed the narrowing of attributes using :only # and :except on Base#attributes @@ -41,6 +41,7 @@ def self.strip(record, options) if options allow_empty = options[:allow_empty] collapse_spaces = options[:collapse_spaces] + regex = options[:regex] end attributes.each do |attr, value| @@ -53,6 +54,10 @@ def self.strip(record, options) if collapse_spaces && value.respond_to?(:squeeze!) value.squeeze!(' ') end + + if regex && value.respond_to?(:gsub!) + value.gsub!(regex, '') + end record[attr] = value if original_value != value end diff --git a/test/strip_attributes_test.rb b/test/strip_attributes_test.rb index 10135e8..ddc0dd5 100644 --- a/test/strip_attributes_test.rb +++ b/test/strip_attributes_test.rb @@ -56,6 +56,11 @@ class CoexistWithOtherValidations < Tableless } end +class StripRegexMockRecord < Tableless + include MockAttributes + strip_attributes :regex => /[\^\%&\*]/ +end + class StripAttributesTest < MiniTest::Unit::TestCase def setup @init_params = { :foo => "\tfoo", :bar => "bar \t ", :biz => "\tbiz ", :baz => "", :bang => " ", :foz => " foz foz" } @@ -169,4 +174,12 @@ def test_should_coexist_with_other_validations # assert record.valid?, "Expected record to be valid, but got #{record.errors.full_messages}" # assert !record.errors.include?(:number), "Expected record to have no errors on :number" end + + def test_should_strip_regex + record = StripRegexMockRecord.new + record.assign_attributes(@init_params.merge(:foo => "^%&*abc ")) + record.valid? + assert_equal "abc", record.foo + assert_equal "bar", record.bar + end end