Stripping strings in a Mongoid document

When taking in user input on a web form you usually want to strip/trim the text the user has entered. I wrote a little Mongoid extension class to do this. The fields need to explicitly declared for this to work. To use it just add include Mongoid::StringStripper to your document class.

module Mongoid
  module StringStripper
    extend ActiveSupport::Concern

      included do
        set_callback :save, :before, :strip_strings

      def strip_strings
        field_names = {|x| x[0] }.reject{ |x| x[0] == "_"  }
        field_names.each do |field_name|
          value = self.send(field_name)
          if value and value.respond_to?(:strip)
            self.send(field_name + "=", value.strip)

Here is usage example/test:

require 'test_helper'

class TestStippee
  include Mongoid::Document
  include Mongoid::StringStripper

  field :a, type: String
  field :b, type: String
  field :c, type: Integer


class StringStripperTest < ActiveSupport::TestCase
  test "When mongoid doc is saved the strings are stripped" do
    o = => "stripped ", :b => "unchanged", :c => 1)
    assert_equal o.a, "stripped"
    assert_equal o.b, "unchanged"
    assert_equal o.c, 1

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s