module NormalizeAttributes

Public Class Methods

apply_normalizers(record, attribute, normalizers, options) click to toggle source
# File lib/normalize_attributes/callbacks.rb, line 27
def self.apply_normalizers(record, attribute, normalizers, options)
  value = NormalizeAttributes.retrieve_value(record, attribute, options[:raw])
  normalizers = NormalizeAttributes.retrieve_normalizers(normalizers, value)

  normalizers.each do |normalizer|
    if normalizer.respond_to?(:call)
      value = normalizer.call(value)
    elsif value.respond_to?(normalizer)
      value = value.send(normalizer)
    elsif record.respond_to?(normalizer)
      value = record.send(normalizer, value)
    end
  end

  begin
    record.send(:write_attribute, attribute, value)
  rescue ActiveModel::MissingAttributeError
    record.public_send("#{attribute}=", value)
  end
end
retrieve_normalizers(normalizers, value) click to toggle source
# File lib/normalize_attributes/callbacks.rb, line 14
def self.retrieve_normalizers(normalizers, value)
  return normalizers unless normalizers.empty?

  case value
  when String
    [:squish]
  when Array
    [:compact]
  else
    []
  end
end
retrieve_value(record, attribute, raw) click to toggle source
# File lib/normalize_attributes/callbacks.rb, line 4
def self.retrieve_value(record, attribute, raw)
  before_type_cast_method = "#{attribute}_before_type_cast"

  if raw && record.respond_to?(before_type_cast_method)
    record.send(before_type_cast_method)
  else
    record.send(attribute)
  end
end