Class: ActiveCleaner::BaseCleaner

Inherits:
Object
  • Object
show all
Defined in:
lib/active_cleaner/base_cleaner.rb

Overview

The base cleaner.

Every cleaner inherit from it.

class MyCleaner < ActiveCleaner::BaseCleaner

  def clean_value(old_value, record = nil)
    old_value.gsub("foo", "bar")
  end

end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attr_name, options = {}) ⇒ BaseCleaner

Accepts options that will be made available through the options reader.



24
25
26
27
28
29
# File 'lib/active_cleaner/base_cleaner.rb', line 24

def initialize(attr_name, options = {})
  @attr_name = attr_name
  @options = {
    nilify: false,
  }.merge(options).freeze
end

Instance Attribute Details

#attr_nameObject (readonly)

Attribute name



18
19
20
# File 'lib/active_cleaner/base_cleaner.rb', line 18

def attr_name
  @attr_name
end

#optionsObject (readonly)

Options given to the cleaner.



21
22
23
# File 'lib/active_cleaner/base_cleaner.rb', line 21

def options
  @options
end

Class Method Details

.kindObject

The kind of the cleaner.



32
33
34
# File 'lib/active_cleaner/base_cleaner.rb', line 32

def self.kind
  @kind ||= name.split("::").last.underscore.sub(/_cleaner$/, "").to_sym
end

Instance Method Details

#==(other) ⇒ Object

Test whether or not two cleaners are equal.



69
70
71
# File 'lib/active_cleaner/base_cleaner.rb', line 69

def ==(other)
  kind == other.kind && attr_name == other.attr_name && options == other.options
end

#clean(record) ⇒ Object

Cleans the record by extracting the value of the field, cleaning it, and setting it back.



42
43
44
45
46
47
48
49
50
# File 'lib/active_cleaner/base_cleaner.rb', line 42

def clean(record)
  value = record.read_attribute_for_cleaning(attr_name)

  new_value = clean_value(value, record)

  new_value = nil if @options[:nilify] && nilify_value?(new_value, record)

  record.write_attribute_after_cleaning(attr_name, new_value) unless new_value == value
end

#clean_value(_old_value, _record = nil) ⇒ Object

Cleans the value.

It is expected that the returned value is the cleaned value.

The method needs to be implemented in the subclasses.

Raises:

  • (NotImplementedError)


57
58
59
# File 'lib/active_cleaner/base_cleaner.rb', line 57

def clean_value(_old_value, _record = nil)
  raise NotImplementedError, "Subclasses must implement a clean(value, record=nil) method."
end

#kindObject

The kind of the cleaner.



37
38
39
# File 'lib/active_cleaner/base_cleaner.rb', line 37

def kind
  self.class.kind
end

#nilify_value?(value, _record = nil) ⇒ Boolean

Tests whether or not the value should be nilified.

This can be changed in the subclasses.

Returns:

  • (Boolean)


64
65
66
# File 'lib/active_cleaner/base_cleaner.rb', line 64

def nilify_value?(value, _record = nil)
  value == ""
end