Class: ActiveCleaner::TextCleaner

Inherits:
BaseCleaner show all
Defined in:
lib/active_cleaner/text_cleaner.rb

Overview

TextCleaner

Cleans a string by squishing all the extra space characters, but preserves new lines (with a max of 2 successive new lines).

Useful when the field is rendered with the simple_format Rails helper.

It turns " My first line \n My second line \t " into "My first line\nMy second line".

Options

:nilify

Whether or not set the field to nil when the field was or is cleaned to "". Default to false.

Example

class Article
  include ActiveCleaner

  clean :body, as: :text
end

article = Article.new(body: "   My first paragraph \n   \n  \t \n My second paragraph,  \n longer.  \t  ")
article.save
article.body
# => "My first paragraph\n\nMy second paragraph,\nlonger."

Instance Attribute Summary

Attributes inherited from BaseCleaner

#attr_name, #options

Instance Method Summary collapse

Methods inherited from BaseCleaner

#==, #clean, #initialize, kind, #kind, #nilify_value?

Constructor Details

This class inherits a constructor from ActiveCleaner::BaseCleaner

Instance Method Details

#clean_value(old_value, _record = nil) ⇒ Object

Cleans the value.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/active_cleaner/text_cleaner.rb', line 34

def clean_value(old_value, _record = nil)
  case old_value
  when String
    value = old_value.dup

    value.strip!

    # clean the new lines mess among OS
    value.gsub!(/\r\n|\r/, "\n")

    # protect stuff to keep with a markup
    value.gsub!(/\n/, "__NEW_LINE__")

    value.gsub!(/\s+/, " ")
    value.gsub!(/ ?__NEW_LINE__ ?/, "__NEW_LINE__")
    value.gsub!(/(__NEW_LINE__){3,}/, "__NEW_LINE____NEW_LINE__")

    # reverse the safe markup
    value.gsub!(/__NEW_LINE__/, "\n")

    value
  else
    old_value
  end
end