Module: Varify::Base
- Defined in:
- lib/varify/base.rb
Constant Summary collapse
- RULES =
{ required: Varify::Rules::RequiredRule, is_a: Varify::Rules::IsARule, one_of: Varify::Rules::OneOfRule, between: Varify::Rules::BetweenRule }
Class Method Summary collapse
-
.callback {|| ... } ⇒ Object
Sets the callback for when a validation fails.
-
.fail(options = {}) ⇒ Object
private
Used by the varify method to send error messages to the callback.
-
.varify(param_key, params = {}, options = {}, &block) ⇒ Object
Processes the input parameter.
Class Method Details
.callback {|| ... } ⇒ Object
Sets the callback for when a validation fails
20 21 22 |
# File 'lib/varify/base.rb', line 20 def self.callback(&block) @callback = block end |
.fail(options = {}) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Used by the varify method to send error messages to the callback
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/varify/base.rb', line 30 def self.fail(={}) = .is_a?(String) ? : [:message] raise "Fail (fail) requires a string message or hash with :message" unless raise "Key (:key) is required in calling fail" unless [:key] raise "Rule (:rule) is required in calling fail" unless [:rule] error = { message: , key: [:key], rule: [:rule] } if @callback @callback.call(error) else raise ArgumentError, end end |
.varify(param_key, params = {}, options = {}, &block) ⇒ Object
Processes the input parameter
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/varify/base.rb', line 54 def self.varify(param_key, params={}, ={},&block) value = params[param_key] || [:default] name = params[:name] || param_key.to_s.split('_').map{|e| e.capitalize}.join(' ') required = [:required] rules = {} rules_to_process = .dup rules_to_process.delete(:default) rules_to_process.delete(:name) if value || required rules_to_process.each do |rule_key,rule_value| rule_class = RULES[rule_key] raise "Rule ':#{rule_key}' is not defined" unless rule_class rules[rule_key] = rule_class.new(param_key,name,value,rule_value) end rules.each do |rule_key,rule| fail(message: rule., key: param_key, rule:rule_key) unless rule.valid? end end value end |