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:



66
67
68
69
# File 'lib/validy.rb', line 66

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

Parameters:

  • or callable object which will be triggered for validation

  • (defaults to: nil)

    definition



87
88
89
90
91
92
93
# File 'lib/validy.rb', line 87

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:



79
80
81
# File 'lib/validy.rb', line 79

def errors
  @errors
end

#optional(attribute) ⇒ Object

“optional” starts void validation for the given attribute

Parameters:

  • a target one



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

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

Parameters:

  • a target one

  • (defaults to: nil)

    custom defined error message



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

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

Parameters:

  • for checking type of the target attribute

  • (defaults to: nil)

    custom defined error message



120
121
122
123
124
125
126
# File 'lib/validy.rb', line 120

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:



73
74
75
# File 'lib/validy.rb', line 73

def valid?
  @valid
end