Module: Fustrate::Rails::Concerns::CleanAttributes

Extended by:
ActiveSupport::Concern
Defined in:
lib/fustrate/rails/concerns/clean_attributes.rb

Constant Summary collapse

STRING_TYPES =
%i[string text citext].freeze

Class Method Summary collapse

Class Method Details

.clean_record(record) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/fustrate/rails/concerns/clean_attributes.rb', line 35

def self.clean_record(record)
  string_columns(record.class).each do |attribute|
    next unless record[attribute]

    record[attribute] = strip record[attribute]
  end
end

.string_columns(klass) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/fustrate/rails/concerns/clean_attributes.rb', line 23

def self.string_columns(klass)
  # There's no reason to clean polymorphic type columns
  polymorphic_type_columns = klass.reflect_on_all_associations
    .select { _1.options[:polymorphic] }
    .map { "#{_1.name}_type" }

  klass.columns
    .select { self::STRING_TYPES.include?(_1..type) }
    .reject { polymorphic_type_columns.include?(_1.name) }
    .map(&:name)
end

.strip(text) ⇒ Object

Collapse multiple spaces, remove leading/trailing whitespace, and remove carriage returns



15
16
17
18
19
20
21
# File 'lib/fustrate/rails/concerns/clean_attributes.rb', line 15

def self.strip(text)
  return text.map { strip(_1) } if text.is_a?(::Array)

  return if text.blank?

  text.strip.gsub(/ {2,}/, ' ').gsub(/^[ \t]+|[ \t]+$/, '').gsub(/\r\n?/, "\n").gsub(/\n{3,}/, "\n\n")
end