All Projects â†’ rmm5t â†’ Strip_attributes

rmm5t / Strip_attributes

Licence: mit
🔪 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.

Programming Languages

ruby
36898 projects - #4 most used programming language

Projects that are alternatives of or similar to Strip attributes

Graphql devise
GraphQL interface on top devise_token_auth
Stars: ✭ 100 (-77.32%)
Mutual labels:  activerecord, rails, rubygem
Ar lazy preload
Lazy loading associations for the ActiveRecord models
Stars: ✭ 281 (-36.28%)
Mutual labels:  activerecord, rails
Rails Pg Extras
Rails PostgreSQL database performance insights. Locks, index usage, buffer cache hit ratios, vacuum stats and more.
Stars: ✭ 432 (-2.04%)
Mutual labels:  activerecord, rails
Store model
Work with JSON-backed attributes as ActiveRecord-ish models
Stars: ✭ 410 (-7.03%)
Mutual labels:  activerecord, rails
Public activity
Easy activity tracking for models - similar to Github's Public Activity
Stars: ✭ 2,822 (+539.91%)
Mutual labels:  activerecord, rails
Elasticsearch Rails
Elasticsearch integrations for ActiveModel/Record and Ruby on Rails
Stars: ✭ 2,896 (+556.69%)
Mutual labels:  activerecord, rails
Tapping device
TappingDevice makes objects tell you what they do, so you don't need to track them yourself.
Stars: ✭ 296 (-32.88%)
Mutual labels:  rails, rubygem
Seamless database pool
Add support for master/slave database clusters in ActiveRecord to improve performance.
Stars: ✭ 222 (-49.66%)
Mutual labels:  activerecord, rails
Clearance
Rails authentication with email & password.
Stars: ✭ 3,467 (+686.17%)
Mutual labels:  rails, rubygem
Algoliasearch Rails
AlgoliaSearch integration to your favorite ORM
Stars: ✭ 352 (-20.18%)
Mutual labels:  activerecord, rails
Isolator
Detect non-atomic interactions within DB transactions
Stars: ✭ 362 (-17.91%)
Mutual labels:  activerecord, rails
Clowne
A flexible gem for cloning models
Stars: ✭ 260 (-41.04%)
Mutual labels:  activerecord, rails
Scenic
Scenic is maintained by Derek Prior, Caleb Hearth, and you, our contributors.
Stars: ✭ 2,856 (+547.62%)
Mutual labels:  activerecord, rails
Pluck to hash
Extend ActiveRecord pluck to return array of hashes
Stars: ✭ 275 (-37.64%)
Mutual labels:  activerecord, rails
Activerecord Postgres enum
Integrate PostgreSQL's enum data type into ActiveRecord's schema and migrations.
Stars: ✭ 227 (-48.53%)
Mutual labels:  activerecord, rails
Pg party
ActiveRecord PostgreSQL Partitioning
Stars: ✭ 294 (-33.33%)
Mutual labels:  activerecord, rails
Second level cache
Write Through and Read Through caching library inspired by CacheMoney and cache_fu, support ActiveRecord 4, 5 and 6.
Stars: ✭ 380 (-13.83%)
Mutual labels:  activerecord, rails
Activerecord Turntable
ActiveRecord Sharding Plugin
Stars: ✭ 206 (-53.29%)
Mutual labels:  activerecord, rails
Secondbase
Seamless second database integration for Rails.
Stars: ✭ 216 (-51.02%)
Mutual labels:  activerecord, rails
Html5 validators
A gem/plugin for Rails 3, Rails 4, Rails 5, and Rails 6 that enables client-side validation using ActiveModel + HTML5 Form Validation
Stars: ✭ 302 (-31.52%)
Mutual labels:  activerecord, rails

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 :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 :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 :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 :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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].