Module: AttributeNormalizer::ClassMethods

Defined in:
lib/attribute_normalizer/model_inclusions.rb

Instance Method Summary collapse

Instance Method Details

#inherited(subclass) ⇒ Object



63
64
65
66
67
68
# File 'lib/attribute_normalizer/model_inclusions.rb', line 63

def inherited(subclass)
  super
  if subclass.respond_to?(:table_exists?) && (subclass.table_exists? rescue false)
    subclass.normalize_default_attributes
  end
end

#normalize_attributes(*attributes, &block) ⇒ Object Also known as: normalize_attribute



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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/attribute_normalizer/model_inclusions.rb', line 8

def normalize_attributes(*attributes, &block)
  options = attributes.last.is_a?(::Hash) ? attributes.pop : {}

  normalizers    = [ options.delete(:with) ].flatten.compact

  if normalizers.empty? && !block_given?
    normalizers = AttributeNormalizer.configuration.default_normalizers # the default normalizers
  end

  attributes.each do |attribute|
    if block_given?
      define_method "normalize_#{attribute}" do |value|
        yield(value)
      end
    else
      define_method "normalize_#{attribute}" do |value|
        normalized = value

        normalizers.each do |normalizer_name|
          unless normalizer_name.kind_of?(Symbol)
            normalizer_name, options = normalizer_name.keys[0], normalizer_name[ normalizer_name.keys[0] ]
          end
          normalizer = AttributeNormalizer.configuration.normalizers[normalizer_name]
          raise AttributeNormalizer::MissingNormalizer.new("No normalizer was found for #{normalizer_name}") unless normalizer
          normalized = normalizer.respond_to?(:normalize) ? normalizer.normalize( normalized , options) : normalizer.call(normalized, options)
        end
        normalized
      end
    end

    self.send :private, "normalize_#{attribute}"

    if method_defined?(:"#{attribute}=")
      alias_method "old_#{attribute}=", "#{attribute}="
    end

    define_method "#{attribute}=" do |value|
      begin
        super(self.send(:"normalize_#{attribute}", value))
      rescue NoMethodError
        normalized_value = self.send(:"normalize_#{attribute}", value)
        self.send("old_#{attribute}=", normalized_value)
      end
    end

  end
end

#normalize_default_attributesObject



57
58
59
60
61
# File 'lib/attribute_normalizer/model_inclusions.rb', line 57

def normalize_default_attributes
  AttributeNormalizer.configuration.default_attributes.each do |attribute_name, options|
    normalize_attribute(attribute_name, options) if self.column_names.include?(attribute_name)
  end
end