I came up with a new validator that does truncation. Here is how I did it:
I created the “validators” folder inside the “app” folder, and then created the file “length_truncate_validator.rb” with the following contents:
class LengthTruncateValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) ml = options[:maximum] record.send("#{attribute}=", value.mb_chars.slice(0,ml)) if value.mb_chars.length > ml unless value.nil? or ml.nil? end class << self def maximum(record_class, attribute) ltv = record_class.validators_on(attribute).detect { |v| v.is_a?(LengthTruncateValidator) } ltv.options[:maximum] unless ltv.nil? end end end
And inside my model class, I have something like:
class Book < ActiveRecord::Base validates :title, :length_truncate => {:maximum => 10} end
which is very convenient and works as I need.
But still, if you think that this can be improved or done differently, please.
p.matsinopoulos
source share