Module: ActiveRecord::DatabaseValidations::StringTruncator

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

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Methods included from Validations::AdapterHelper

#mysql_adapter?

Instance Method Details

#truncate_value_to_field_limit(field, value) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/active_record/validations/string_truncator.rb', line 9

def truncate_value_to_field_limit(field, value)
  return value unless mysql_adapter?(self.class.connection)
  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