Module: NormalizeAttributes

Defined in:
lib/normalize_attributes/version.rb,
lib/normalize_attributes/callbacks.rb

Defined Under Namespace

Modules: Callbacks, Version

Class Method Summary collapse

Class Method Details

.apply_normalizers(record, attribute, normalizers, options) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 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, true)
      value = record.send(normalizer, value)
    else
      raise "Unknown normalizer #{normalizer.inspect}"
    end
  end

  record.public_send("#{attribute}=", value)
end

.retrieve_normalizers(normalizers, value) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
# 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) ⇒ Object



4
5
6
7
8
9
10
11
12
# 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