Module: Validy::ClassMethods

Defined in:
lib/validy.rb

Instance Method Summary collapse

Instance Method Details

#validy_on(method:) ⇒ Object



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
# File 'lib/validy.rb', line 33

def validy_on(method:)
  method_with_bang_name = (method[-1] == '!' ? method.to_s : "#{method}!")
  method_without_bang_name = method_with_bang_name.gsub('!', '')

  define_method :method_with_bang do
    method_with_bang_name
  end

  define_method :method_without_bang do
    method_without_bang_name
  end

  hooks = Module.new do
    method_with_bang_name = (method[-1] == '!' ? method.to_s : "#{method}!")
    method_without_bang_name = method_with_bang_name.gsub('!', '')
    define_method method_with_bang_name do |*args, &block|
      if method_presented?(method_without_bang_name)
        send(method_without_bang_name, *args, &block)
      else
        super(*args, &block)
      end
      raise ::Validy::Error, stringified_error unless valid?
    end
  end
  prepend hooks
end