• Stars
    star
    543
  • Rank 78,685 (Top 2 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 16 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🔪 An ActiveModel extension that automatically strips all attributes of leading and trailing whitespace before validation. If the attribute is blank, it strips the value to nil.

StripAttributes

Gem Version Build Status Gem Downloads

StripAttributes is an ActiveModel extension that automatically strips all attributes of leading and trailing whitespace before validation. If the attribute is blank, it strips the value to nil by default.

It works by adding a before_validation hook to the record. By default, all attributes are stripped of whitespace, but :only and :except options can be used to limit which attributes are stripped. Both options accept a single attribute (only: :field) or arrays of attributes (except: [:field1, :field2, :field3]).

It's also possible to skip stripping the attributes altogether per model using the :if and :unless options.

Installation

Include the gem in your Gemfile:

gem "strip_attributes"

Examples

Default Behavior

class DrunkPokerPlayer < ActiveRecord::Base
  strip_attributes
end

Using except

# all attributes will be stripped except :boxers
class SoberPokerPlayer < ActiveRecord::Base
  strip_attributes except: :boxers
end

Using only

# only :shoe, :sock, and :glove attributes will be stripped
class ConservativePokerPlayer < ActiveRecord::Base
  strip_attributes only: [:shoe, :sock, :glove]
end

Using if

# Only records with odd ids will be stripped
class OddPokerPlayer < ActiveRecord::Base
  strip_attributes if: :strip_me?

  def strip_me?
    id.odd?
  end
end

Using unless

# strip_attributes will be applied randomly
class RandomPokerPlayer < ActiveRecord::Base
  strip_attributes unless: :strip_me?

  def strip_me?
    [true, false].sample
  end
end

Using allow_empty

# Empty attributes will not be converted to nil
class BrokePokerPlayer < ActiveRecord::Base
  strip_attributes allow_empty: true
end

Using collapse_spaces

# Sequential spaces in attributes will be collapsed to one space
class EloquentPokerPlayer < ActiveRecord::Base
  strip_attributes collapse_spaces: true
end

Using replace_newlines

# Newlines in attributes will be replaced with a space
class EloquentPokerPlayer < ActiveRecord::Base
  strip_attributes replace_newlines: true
end

Using regex

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]/

  # Strip off all spaces and keep only alphabetic and numeric characters
  strip_attributes only: :nickname, regex: /[^[:alnum:]_-]/

  # Remove trailing whitespace from a multi-line string
  strip_attributes only: :code, regex: /[[:blank:]]+$/)
end

Usage Patterns

Other ORMs implementing ActiveModel

It also works on other ActiveModel classes, such as Mongoid documents:

class User
  include Mongoid::Document
  strip_attributes only: :email
end

Using it with ActiveAttr

class Person
  include ActiveAttr::Model
  include ActiveModel::Validations::Callbacks

  attribute :name
  attribute :email

  strip_attributes
end

Using it directly

# where record is an ActiveModel instance
StripAttributes.strip(record, collapse_spaces: true)

# works directly on Strings too
StripAttributes.strip(" foo \t") #=> "foo"
StripAttributes.strip(" foo   bar", collapse_spaces: true) #=> "foo bar"

Testing

StripAttributes provides an RSpec/Shoulda-compatible matcher for easier testing of attribute assignment. You can use this with RSpec, Shoulda, Minitest-MatchersVaccine (preferred), or Minitest-Matchers.

Setup spec_helper.rb or test_helper.rb

To initialize RSpec, add this to your spec_helper.rb:

require "strip_attributes/matchers"
RSpec.configure do |config|
  config.include StripAttributes::Matchers
end

To initialize Shoulda (with test-unit), add this to your test_helper.rb:

require "strip_attributes/matchers"
class Test::Unit::TestCase
  extend StripAttributes::Matchers
end

OR if in a Rails environment, you might prefer this:

require "strip_attributes/matchers"
class ActiveSupport::TestCase
  extend StripAttributes::Matchers
end

To initialize Minitest-MatchersVaccine, add this to your test_helper.rb:

require "strip_attributes/matchers"
class MiniTest::Spec
  include StripAttributes::Matchers
end

OR if in a Rails environment, you might prefer this:

require "strip_attributes/matchers"
class ActiveSupport::TestCase
  include StripAttributes::Matchers
end

To initialize Minitest-Matchers, add this to your test_helper.rb:

require "strip_attributes/matchers"
class MiniTest::Spec
  include StripAttributes::Matchers
end

Writing Tests

RSpec:

describe User do
  it { is_expected.to strip_attribute(:name).collapse_spaces }
  it { is_expected.to strip_attribute(:name).replace_newlines }
  it { is_expected.to strip_attribute :email }
  it { is_expected.to strip_attributes(:name, :email) }
  it { is_expected.not_to strip_attribute :password }
  it { is_expected.not_to strip_attributes(:password, :encrypted_password)  }
end

Shoulda (with test-unit):

class UserTest < ActiveSupport::TestCase
  should strip_attribute(:name).collapse_spaces
  should strip_attribute(:name).replace_newlines
  should strip_attribute :email
  should strip_attributes(:name, :email)
  should_not strip_attribute :password
  should_not strip_attributes(:password, :encrypted_password)
end

Minitest-MatchersVaccine:

describe User do
  subject { User.new }

  it "should strip attributes" do
    must strip_attribute(:name).collapse_spaces
    must strip_attribute(:name).replace_newlines
    must strip_attribute :email
    must strip_attributes(:name, :email)
    wont strip_attribute :password
    wont strip_attributes(:password, :encrypted_password)
  end
end

Minitest-Matchers:

describe User do
  subject { User.new }

  must { strip_attribute(:name).collapse_spaces }
  must { strip_attribute(:name).replace_newlines }
  must { strip_attribute :email }
  must { strip_attributes(:name, :email) }
  wont { strip_attribute :password }
  wont { strip_attributes(:password, :encrypted_password) }
end

Support

Submit suggestions or feature requests as a GitHub Issue or Pull Request (preferred). If you send a pull request, remember to update the corresponding unit tests. In fact, I prefer new features to be submitted in the form of new unit tests.

Credits

The idea was originally triggered by the information at the (now defunct) Rails Wiki but was modified from the original to include more idiomatic ruby and rails support.

Versioning

Semantic Versioning 2.0 as defined at http://semver.org.

License

MIT License

More Repositories

1

jquery-timeago

🕗 The original jQuery plugin that makes it easy to support automatically updating fuzzy timestamps (e.g. "4 minutes ago").
JavaScript
3,821
star
2

liquidmetal

💦🤘 A mimetic poly-alloy of the Quicksilver scoring algorithm, essentially LiquidMetal. </Schwarzenegger Voice>
JavaScript
291
star
3

dotfiles

●📄 Ryan McGeary's configuration shiznit that makes him productive
Emacs Lisp
283
star
4

jquery-flexselect

💪☑️ A jQuery plugin that turns regular select boxes into Quicksilver-like, flex-matching, incremental-finding controls.
HTML
237
star
5

jquery-sieve

🚰 Sieve is a jQuery plugin allows you to quickly add an interactive search filter to any block of content.
HTML
152
star
6

maxframe.el

↔️↕️ [Elisp] maxframe provides the ability to maximize the emacs frame and stay within the display resolution.
Emacs Lisp
52
star
7

googleapis-mirror

A subset mirror of the Google Libraries API CDN meant to be served from your local development machine when internet access is lacking.
Ruby
46
star
8

minitest-matchers_vaccine

💉 Adds matcher support to minitest without all the other RSpec-style expectation "infections."
Ruby
33
star
9

tilda-bin

〰️🗑️ Ryan McGeary's personal ~/bin directory -- well at least the stuff that he wants to make public.
Ruby
15
star
10

mkv2m4v

📺 Makes Apple TV compatible videos from MKV containers
Ruby
12
star
11

rbenv-rbx

Plugin for rbenv that adds Rubinius 2.x support
Shell
11
star
12

insert-time.el

[Elisp] insert-time provides an easy way to insert time and date stamps into your emacs buffers
Emacs Lisp
11
star
13

ryan.mcgeary.org

🤓 Ryan McGeary's Home Page
HTML
9
star
14

iso639

🌎🌏 A ruby gem for ISO 639-1 and ISO 639-2 lookups by name, alpha-2 code, or alpha-3 code
Ruby
8
star
15

smhelper-obfuscated-email

A staticmatic helper to obfuscate mailto links using javascript.
Ruby
6
star
16

yarg

Yet Another Ruby Generator: Customize existing project generators to fit your personality.
Ruby
6
star
17

rbenv-bundle-path-fix

💎🔧 Fixes a peculiar difference between local and global config of BUNDLE_PATH in Bundler v1
Shell
5
star
18

duplicatorg

Minimal command line client for ReplicatorG
Ruby
4
star
19

boulderruby-startupweek

Boulder Ruby Presentation Demo during Startup Week 2015
Ruby
4
star
20

project-euler

My solutions to Project Euler
Ruby
3
star
21

launch_app_scripts

Automated creation of AppleScripts that launch your favorite applications
3
star
22

zippopotamus

📍 Ruby wrapper gem for the http://Zippopotam.us API.
Ruby
3
star
23

htmlize

Convert buffer text and decorations to HTML
Emacs Lisp
2
star
24

mcgearygroup.com

Home page for McGeary Consulting Group, LLC
HTML
2
star
25

rmm5t.github.io

My GitHub Page (just a redirect to http://ryan.mcgeary.org)
HTML
2
star
26

sprints

Scaffolding for quick development sprints
Ruby
1
star
27

middleman-test

For testing gems related to middleman
Ruby
1
star
28

stackexchange-shortcut-disabler

🔧 Chrome Extension to fix readline/emacs hotkeys in the editor of all StackExchange sites
JavaScript
1
star
29

big4referral

HTML
1
star