How to crop input in rail models around the world

There are several models in my Rails application where users submit data to the database. Many of this data has lagging and leading gaps. Is there a way to globally remove all input and trailing spaces?

I would like to avoid this for every field in every model, there seems to be a global way to handle this in time before_save.

Are there any methods used there?

thank

+3
source share
5 answers

Here is one simple way to do this with the selected attributes:

module ActiveRecord
  module Acts
    module AttributeAutoStripper
      def self.included(base)
        base.extend(ClassMethods)
      end

      module ClassMethods
        def acts_as_attribute_auto_stripper (*names)
          class_eval <<-EOV
            include ActiveRecord::Acts::AttributeAutoStripper::InstanceMethods
            before_validation :auto_strip_selected_attributes
            def auto_strip_attributes
              #{names.inspect}
            end
          EOV
        end
      end
      module InstanceMethods
        def auto_strip_selected_attributes
          if auto_strip_attributes
            auto_strip_attributes.each do |attr_name|
              self.send("#{attr_name}=", self.send(attr_name).to_s.strip) unless self.send(attr_name).blank?
            end
          end
        end
      end
    end
  end
end
ActiveRecord::Base.send :include, ActiveRecord::Acts::AttributeAutoStripper

and then in your model:

class User < ActiveRecord::Base
  acts_as_attribute_auto_stripper :name, :email
end
+2
source

: https://github.com/holli/auto_strip_attributes

, , , , . . .

gem "auto_strip_attributes", "~> 1.0"

class User < ActiveRecord::Base
  auto_strip_attributes :name, :nick, :nullify => false, :squish => true
end

, before_save. ( .) , .

attributes.each do before_validation do ...
  record.send("#{attr_name}=", record.send(attr_name).to_s.strip)

attributes.each do before_validation do ...
  record[attribute] = record.send(attr_name).to_s.strip)

setter ( , before_validation). setter , setter.

+3

, , . .

, :)

0

You can subclass ActiveRecord with a before_save filter that separates all attributes. Then make all your models a subclass of this new class.

0
source

All Articles