Skip to content

Instantly share code, notes, and snippets.

@sharshenov
Created April 10, 2020 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharshenov/59fecda12ae05ed447e306c5b207fb9b to your computer and use it in GitHub Desktop.
Save sharshenov/59fecda12ae05ed447e306c5b207fb9b to your computer and use it in GitHub Desktop.
Truncate string attributes to database limit in Rails
# frozen_string_literal: true
# Usage:
# Place it in app/models/concerns dir
#
# Include in class
# class Product < ApplicationRecord
# include Truncatable
# end
#
# Product.find(123).update(title: 'a' * 100) # title will be truncated to database column limit size
module Truncatable
extend ActiveSupport::Concern
OMISSION = '…'
included do
before_save :truncate_string_attributes
end
private
def truncate_string_attributes
self.class.columns.each do |column|
next unless column.type == :string && column.limit
truncate_value_for_attribute(name: column.name, limit: column.limit)
end
end
def truncate_value_for_attribute(name:, limit:)
case (value = self[name])
when String
return if value.length < limit
self[name] = value.truncate(limit, omission: OMISSION)
when Array
return if value.all? { |v| v.length < limit }
self[name] = value.map { |v| v.truncate(limit, omission: OMISSION) }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment