Module: Validy::InstanceMethods

Defined in:
lib/validy.rb

Instance Method Summary collapse

Instance Method Details

#add_error(args = {}) ⇒ FalseClass

“add_error” adds an error and set valid state to false

Returns:

  • (FalseClass)


64
65
66
67
# File 'lib/validy.rb', line 64

def add_error(args = {})
  @errors.merge!(args)
  @valid = false
end

#condition(method, error = nil, &block) ⇒ Object

“condition” evaluates either passed block or instance method represented in the instance



82
83
84
85
86
87
88
# File 'lib/validy.rb', line 82

def condition(method, error = nil, &block)
  return self unless valid?

  condition = method.respond_to?(:call) ? method.call : send(method)
  validate_condition(condition, error, &block)
  self
end

#errorsHash

“errors” returns errors hash

Returns:

  • (Hash)


77
78
79
# File 'lib/validy.rb', line 77

def errors
  @errors
end

#optional(attribute) ⇒ Object

“optional” starts void validation for the given attribute



100
101
102
103
104
105
# File 'lib/validy.rb', line 100

def optional(attribute)
  return self unless valid?

  @evaluating_attribute = instance_variable_get("@#{attribute}")
  self
end

#required(attribute, error = nil, &block) ⇒ Object

“required” checks presence of the variable



91
92
93
94
95
96
97
# File 'lib/validy.rb', line 91

def required(attribute, error = nil, &block)
  return self unless valid?

  @evaluating_attribute = instance_variable_get("@#{attribute}")
  validate_condition(@evaluating_attribute, error || "#{attribute} required!", &block)
  self
end

#type(clazz, error = nil, &block) ⇒ Object

“type” validates type of the instance variable



108
109
110
111
112
113
114
# File 'lib/validy.rb', line 108

def type(clazz, error = nil, &block)
  return self unless valid?

  validate_condition(@evaluating_attribute&.is_a?(clazz),
                     error || "`#{@evaluating_attribute}` is not a type #{clazz}", &block)
  self
end

#valid?Boolean

“valid?” returns inner valid state

Returns:

  • (Boolean)


71
72
73
# File 'lib/validy.rb', line 71

def valid?
  @valid
end