Skip to content

Commit

Permalink
Merge pull request #14 from dfguo/master
Browse files Browse the repository at this point in the history
add regular expression support
  • Loading branch information
rmm5t committed Jan 15, 2014
2 parents 64c6b7a + 10fbd7a commit 962cef4
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
7 changes: 6 additions & 1 deletion lib/strip_attributes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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|
Expand All @@ -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
Expand Down
13 changes: 13 additions & 0 deletions test/strip_attributes_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down Expand Up @@ -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

0 comments on commit 962cef4

Please sign in to comment.