Module: Scratch::Concerns::Normalize::ClassMethods

Defined in:
lib/scratch/concerns/normalize.rb

Instance Method Summary collapse

Instance Method Details

#normalize(options = {}) ⇒ Object



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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/scratch/concerns/normalize.rb', line 26

def normalize(options = {})
  callback_options = HashWithIndifferentAccess.new options

  options   = callback_options.slice!(:if, :unless)
  default   = options[:default]
  method    = options[:method]
  predicate = Array.wrap options[:predicate]
  callback  = options.fetch_or(:before, :after, :callback,
                               default: :validation)

  callback_method = options[:name] ||
    "normalize_before_#{callback}" +
    (predicate.empty? ? '' : "_when_#{predicate}")

  attributes = options[:attributes] ||
    Scratch::Options
      .except_only(options, normalize_default_attributes_source[self])

  instance_eval do
    define_method callback_method do
      attributes.each do |attribute|
        value = send(attribute)
        if predicate.empty? || value.send(*predicate)
          value =
            if options.has_key? :default
              default
            elsif method
              value.send method
            else
              yield value
            end

          send "#{attribute}=", value
        end
      end
    end
  end

  callback_format = options[:callback_format] ||
    normalize_default_callback_format

  callback = callback_format ? callback_format % callback : callback
  send callback, callback_method
end