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

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

Instance Method Summary collapse

Instance Method Details

#normalize(options = {}) ⇒ Object



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

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

  options   = callback_options.slice!(:if, :unless)
  set       = options[:set]
  method    = options[:method]
  predicate = Array.wrap options[:when]

  trigger_format = options[:trigger_format] || '%s_%s'

  trigger = options[:trigger] ||
    (options[:before] ? trigger_format % [:before , options[:before]] :
     options[:after]  ? trigger_format % [:after  , options[:after]]  :
     raise(ArgumentError, 'missing option, you must specify one of: ' +
           'before, after or trigger'))

  unless options.has_key?(:set) || method || block_given?
    raise(ArgumentError, 'missing option or block, ' +
          'you must give a block or specify one of: set or method')
  end

  callback = options[:name] || Scratch::Utils.gensym

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

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

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

  send trigger, callback
end