Module: AFCSalesforce::Tools::Validation::Rule
- Included in:
- Validator
- Defined in:
- lib/afc_salesforce/tools/validation/validator.rb,
lib/afc_salesforce/tools/validation/rule/email.rb,
lib/afc_salesforce/tools/validation/rule/phone.rb,
lib/afc_salesforce/tools/validation/rule/length.rb,
lib/afc_salesforce/tools/validation/rule/matches.rb,
lib/afc_salesforce/tools/validation/rule/not_nil.rb,
lib/afc_salesforce/tools/validation/rule/numeric.rb,
lib/afc_salesforce/tools/validation/rule/not_empty.rb,
lib/afc_salesforce/tools/validation/rule/instance_of.rb,
lib/afc_salesforce/tools/validation/rule/regular_expression.rb
Defined Under Namespace
Classes: Email, InstanceOf, Length, Matches, NotEmpty, NotNil, Numeric, Phone, RegularExpression
Instance Method Summary collapse
-
#errors ⇒ Object
A hash of errors for this object.
-
#rule(field, definition) ⇒ Object
Define a rule for this object.
-
#rules ⇒ Object
A hash of rules for this object.
-
#valid? ⇒ Boolean
Determines if this object is valid.
Instance Method Details
#errors ⇒ Object
A hash of errors for this object
11 12 13 |
# File 'lib/afc_salesforce/tools/validation/validator.rb', line 11 def errors @errors ||= {} end |
#rule(field, definition) ⇒ Object
Define a rule for this object
The rule parameter can be one of the following:
-
a symbol that matches to a class in the AFCSalesforce::Tools::Validation::Rules namespace
-
e.g. rule(:field, :not_empty)
-
-
a hash containing the rule as the key and it’s parameters as the values
-
e.g. rule(:field, :length => { minimum: 3, maximum: 5 })
-
-
an array combining the two previous types
-
e.g. rule(:field, [:not_empty, length: { minimum: 3, maximum: 5}])
-
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/afc_salesforce/tools/validation/validator.rb', line 25 def rule(field, definition) field = field.to_sym rules[field] = [] if rules[field].nil? if definition.respond_to?(:each_pair) add_parameterized_rules(field, definition) elsif definition.respond_to?(:each) definition.each do |item| if item.respond_to?(:each_pair) add_parameterized_rules(field, item) else add_single_rule(field, item) end end else add_single_rule(field, definition) end self end |
#rules ⇒ Object
A hash of rules for this object
6 7 8 |
# File 'lib/afc_salesforce/tools/validation/validator.rb', line 6 def rules @rules ||= {} end |
#valid? ⇒ Boolean
Determines if this object is valid. When a rule fails for a field, this will stop processing further rules. In this way, you’ll only get one error per field
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/afc_salesforce/tools/validation/validator.rb', line 49 def valid? valid = true rules.each_pair do |field, rules| if ! @obj.respond_to?(field) raise InvalidKey, "cannot validate non-existent field '#{field}'" end rules.each do |r| value = @obj.send(field) if !r.valid_value?(value) valid = false errors[field] = {rule: r.error_key}.merge(r.error(value)) break end end end @valid = valid end |