Provide a ActiveModel::Validations style set of helpers for models to add input filters that work on all dirty fields before validation.
The point of this is I have a project that requires some data consistency and right now that's all ad-hoc and messy. I need a better way to quickly ensure that a username is lower case, things are trimmed properly before stored in the db, etc. Right now that's all done manually on the controller or model, or not at all.
class Example < Activerecord::Base filters :first_name, :trim => true, :alpha => true filters :username, :trim => true, :lowercase => true filters :last_name do |value| value.gsub /steve/, 'foo' end end
- Filters, when defined, get added to a class var array
- Filters are run and applied before validation
- Filters only are run on dirty attributes
Should be able to pass a block to create your own filter:
filters :title { |value| value.titleize }
Should be able to pass multiple attributes with the same filters method:
filters :username, :first_name, :last_name, trim: true
Only allows alphabet chars
filters :url_segment, alpha: true
Converts all chars to lowercase
filters :username, lowercase: true
Converts all chars to uppercase
filters :content, uppercase: true
Removes whitespace from beginning and end of string
filters :content, trim: true
Removes everything except alphabetic characters and numerical digits
filters :content, alphanumeric: true
Removes everything except numerical digits
filters :content, number: true
Removes all html tags
filters :content, striptags: true
Can be passed an only array:
filters :content, striptags: { only: [ 'script' ] }
Or an except array:
filters :content, striptags: { except: [ 'strong', 'em', 'u', 'i', 'b' ] }
Removes all new line characters
filters :content, stripnewlines: true
Gsub replace:
filters :content, gsub: { match: /badword/, replace: '***' }