Module: TruncateToDbLimit
- Extended by:
- ActiveSupport::Concern
- Included in:
- Referent, ServiceResponse
- Defined in:
- lib/truncate_to_db_limit.rb
Overview
An ActiveRecord extension that will let you automatically truncate certain attributes to the maximum length allowed by the DB.
require 'truncate_to_db_limit'
class Something < ActiveRecord::Base
include TruncateToDbLimit
truncate_to_db_limit :short_attr, :short_attr2
#...
Truncation is done in a before_validate hook, so won’t happen until you try to save.
Instance Method Summary collapse
Instance Method Details
#do_truncate_to_db_limit! ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/truncate_to_db_limit.rb', line 29 def do_truncate_to_db_limit! self.class._truncate_to_db_limit_attributes.each do |attribute_name| ar_attr = self.class.columns_hash[attribute_name.to_s] unless ar_attr raise ArgumentError.new("truncate_to_db_limit #{attribute_name}: No such attribute") end limit = ar_attr.limit unless limit && limit.to_i != 0 return # we can do nothing #raise ArgumentError.new("truncate_to_db_limit #{attribute_name}: Limit not known") end normalized = send(attribute_name).try {|v| v.slice(0, limit)} send("#{attribute_name}=", normalized) end end |