Created
April 10, 2020 13:18
-
-
Save sharshenov/59fecda12ae05ed447e306c5b207fb9b to your computer and use it in GitHub Desktop.
Truncate string attributes to database limit in Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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