Sha256: 2618a4012d6a7aac6167261b2f9bd23b2df1fc1e16caa9838dde0c5d05edf1af

Contents?: true

Size: 1.04 KB

Versions: 1

Compression:

Stored size: 1.04 KB

Contents

module ActiveRecord
  module DatabaseValidations
    module StringTruncator
      extend ActiveSupport::Concern

      module ClassMethods
        def truncate_string(field)
          method_name = :"truncate_#{field}_at_database_limit"
          define_method(method_name) do
            return unless self.changes.key?(field.to_s)
            return if self[field].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(self[field], encoding)

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

            return # to make sure the callback chain doesn't halt
          end
          return method_name
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
activerecord-databasevalidations-0.2.3 lib/active_record/validations/string_truncator.rb