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
      end

      def strip_strings
        field_names = fields.map {|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)
          end
        end
      end
  end
end

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

end

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

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s