rails rewrite validation helper

1.ruby rewirte class method

class Computer
end
load 'computer.rb'
c = Computer.new
c.respond_to?(to_s) # => false
c.to_s # => #<Computer:0x28e5568>
#rewirte to_s method to Computer Class
Computer.class_eval do
	def to_s
		puts "rewrite method"
	end
end
c.to_s # => rewrite method


#add new method to Computer Class
c.respond_to?(:new_method) # => false
Computer.class_eval do
	def new_method
		puts "new method"
	end
end
c.new_method # => new method

2.rails rewrite validation helper

这里以重写validates_presence_of为例进行说明。

向config/initializers/new_rails_defaults.rb中添加代码。

## 向ActiveRecord::Errors类中加入add_on_blank_and_full_width_space方法
  ActiveRecord::Errors.class_eval do
    def add_on_blank_or_full_width_space(attributes, msg = @@default_error_messages[:blank])
      for attr in [attributes].flatten
        value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
        add(attr, msg) if value.blank? || value.to_s.gsub(/( | )/,"") == "" #全角空格也报错
      end
    end
  end
  
  ## 重写ActiveRecord::Validations::ClassMethods module的validates_presence_of方法
  ActiveRecord::Validations::ClassMethods.class_eval do

    def validates_presence_of(*attr_names)
        configuration = { :message => ActiveRecord::Errors.default_error_messages[:blank], :on => :save }
        configuration.update(attr_names.extract_options!)

        # can't use validates_each here, because it cannot cope with nonexistent attributes,
        # while errors.add_on_empty can
        send(validation_method(configuration[:on]), configuration) do |record|
          record.errors.add_on_blank_or_full_width_space(attr_names, configuration[:message])
        end
      end
     
  end

model类中使用重写后的validates_presence_of方法,这时:name中如果只输入全角空格会被认为什么都没输入。

class Client < ActiveRecord::Base do
validates_presence_of :name
end



你可能感兴趣的:(rails rewrite validation helper)