Skip to content

Instantly share code, notes, and snippets.

@stevedev
Created May 22, 2013 15:13
Show Gist options
  • Save stevedev/5628358 to your computer and use it in GitHub Desktop.
Save stevedev/5628358 to your computer and use it in GitHub Desktop.
ActiveModel Filters idea

ActiveModel::Filters

Overview

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.

Example Usage

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

Implementation Ideas

  • Filters, when defined, get added to a class var array
  • Filters are run and applied before validation
  • Filters only are run on dirty attributes

Block syntax

Should be able to pass a block to create your own filter:

  filters :title { |value| value.titleize }

Multiple attributes per filters statement:

Should be able to pass multiple attributes with the same filters method:

  filters :username, :first_name, :last_name, trim: true

Default filters

alpha

Only allows alphabet chars

  filters :url_segment, alpha: true

lowercase

Converts all chars to lowercase

  filters :username, lowercase: true

uppercase

Converts all chars to uppercase

  filters :content, uppercase: true

trim

Removes whitespace from beginning and end of string

  filters :content, trim: true

alphanumeric

Removes everything except alphabetic characters and numerical digits

  filters :content, alphanumeric: true

number

Removes everything except numerical digits

  filters :content, number: true

striptags

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' ] }

stripnewlines

Removes all new line characters

  filters :content, stripnewlines: true

gsub

Gsub replace:

  filters :content, gsub: { match: /badword/, replace: '***' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment