ActiveRecord: so that all text fields have a strip that is called on them before saving, unless otherwise specified

Over the years, I came across various problems with various sites when users put spaces at the beginning / end of lines and text fields. Sometimes they cause formatting and layout problems, sometimes they cause search problems (i.e. the search order doesn’t look right even if it’s not), sometimes they actually cause the application to crash.

I thought that it would be useful, instead of inserting a bunch of previous before_save callbacks, as it was in the past, add some ActiveRecord functions to automatically call .strip in any string / text fields before saving, unless I say this so, for example, with do_not_strip :field_x, :field_yor something like that at the top of the class definition.

Before I go and find out how to do this, did anyone see a more pleasant solution? To be clear, I already know that I can do this:

before_save :strip_text_fields

def strip_text_fields
  self.field_x.strip!
  self.field_y.strip!
end

but i'm looking for a better way.

cheers max

+5
source share
3 answers

. , , , - . :

class Story < ActiveRecord::Base
  strip_strings :title, :abstract, :text
end
+1

, lib . , , strip!, . , .

# lib/attribute_stripping.rb
module AttributeStripping

  def self.included(context)
    context.send :before_validation, :strip_whitespace_from_attributes
  end

  def strip_whitespace_from_attributes
    attributes.each_value { |v| v.strip! if v.respond_to? :strip! }
  end

end

:

class MyModel < ActiveRecord::Base
    include AttributeStripping

    # ...
end

(9/10/2013):

, , . . :

module AttributeStripper

  def self.before_validation(model)
    model.attributes.each_value { |v| v.strip! if v.respond_to? :strip! }
    true
  end

end

:

class MyModel < ActiveRecord::Base
  before_validation AttributeStripper

  # ...
end

, .

+10

.

.

, , - . , . (destripped), .

- () - , .. , , . , , , .

+2
source

All Articles