module AutoStripAttributes

Constants

VERSION

Public Instance Methods

auto_strip_attributes(*attributes) click to toggle source
# 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