Module: ActiveRecord::DatabaseValidations::StringTruncator

Extended by:
ActiveSupport::Concern
Defined in:
lib/active_record/validations/string_truncator.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#truncate_value_to_field_limit(field, value) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/active_record/validations/string_truncator.rb', line 6

def truncate_value_to_field_limit(field, value)
  return if value.nil?

  column = self.class.columns_hash[field.to_s]
  maximum, type, encoding = ActiveRecord::DatabaseValidations::MySQL.column_size_limit(column)
  value = ActiveRecord::DatabaseValidations::MySQL.value_for_column(value, encoding)

  case type
  when :characters
    value = value.slice(0, maximum) if maximum && value.length > maximum
  when :bytes
    value = value.mb_chars.limit(maximum).to_s if maximum && value.bytesize > maximum
  end

  value
end