Skip to content
Michael Chaney edited this page May 20, 2020 · 11 revisions

AutoStripAttributes Custom Filter Recipes

The gem is kept small and simple by choice. See the manual at https://github.com/holli/auto_strip_attributes/ .

This page includes some custom filters that were not included in the gem as options but might otherwise be helpful. See https://github.com/holli/auto_strip_attributes#custom-filters for more info.

Truncate Strings and using custom options in filter

See https://github.com/holli/auto_strip_attributes/pull/27 for more info

AutoStripAttributes::Config.setup do
  set_filter(:truncate) do |value, options|
    if !value.blank? && value.respond_to?(:truncate)
      value.truncate(options[:length], omission: options[:omission])
    else
      value
    end
  end
end

class Message < ActiveRecord::Base
  auto_strip_attributes :title, truncate: {length: 5, separator: " ", omission: "…"}
end

Titleize

AutoStripAttributes::Config.setup do
  set_filter(titleize: false) do |value|
    !value.blank? && value.respond_to?(:titleize) ? value.titleize : value
  end
end

Stripping Html tags

AutoStripAttributes::Config.setup do
  set_filter(strip_html: false) do |value|
    ActionController::Base.helpers.strip_tags value
  end
end

Removing utf8 4 bit chars

Good if you are using Mysql utf8 columns in database instead of utf8mb4

AutoStripAttributes::Config.setup do
  set_filter(strip_4_byte_chars: false) do |value|
    !value.blank? && value.respond_to?(:each_char) ? value.each_char.select{|c| c.bytes.count < 4 }.join('') : value
  end
end

Replacing Unicode "curly quotes" with standard ASCII characters

AutoStripAttributes::Config.setup do
  set_filter(fix_curly_quotes: false) do |value|
    !value.blank? && value.respond_to?(:gsub) ?  value.gsub(/[\u201c\u201d]/, '"').gsub(/[\u2018\u2019]/, '\'') : value
  end
end

Force input to lowercase

AutoStripAttributes::Config.setup do
  set_filter(force_downcase: false) do |value|
    !value.blank? && value.respond_to?(:downcase) && value =~ /[[:upper:]]/ ? value.downcase : value
  end
end