Module: Validy::ClassMethods

Defined in:
lib/validy.rb

Instance Method Summary collapse

Instance Method Details

#validy_on(method:) ⇒ Object

validation state

Parameters:

  • method (String)
    • indicates custom, must be implemented method for which will be triggered for defining



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

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