Module: AutoStripAttributes

Defined in:
lib/auto_strip_attributes.rb,
lib/auto_strip_attributes/version.rb

Defined Under Namespace

Classes: Config

Constant Summary collapse

VERSION =
"2.6.0"

Instance Method Summary collapse

Instance Method Details

#auto_strip_attributes(*attributes) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/auto_strip_attributes.rb', line 4

def auto_strip_attributes(*attributes)
  options = AutoStripAttributes::Config.filters_enabled
  if attributes.last.is_a?(Hash)
    options = options.merge(attributes.pop)
  end

  # option `:virtual` is needed because we want to guarantee that
  # getter/setter methods for an attribute will _not_ be invoked by default
  virtual = options.delete(:virtual)

  attributes.each do |attribute|
    before_validation(options) do |record|
      if virtual
        value = record.public_send(attribute)
      else
        value = record[attribute]
      end
      AutoStripAttributes::Config.filters_order.each do |filter_name|
        next if !options[filter_name]
        filter = lambda { |original| AutoStripAttributes::Config.filters[filter_name].call(original, options[filter_name]) }
        value = if value.respond_to?(:is_a?) && value.is_a?(Array)
          array = value.map { |item| filter.call(item) }.compact
          options[:nullify_array] && array.empty? ? nil : array
        else
          filter.call(value)
        end
        if virtual
          record.public_send("#{attribute}=", value)
        else
          record[attribute] = value
        end
      end
    end
  end
end