Module: Arkenstone::Validation::ClassMethods

Defined in:
lib/arkenstone/validation/validations.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#custom_validatorsObject

Returns the value of attribute custom_validators.



146
147
148
# File 'lib/arkenstone/validation/validations.rb', line 146

def custom_validators
  @custom_validators
end

#fields_to_validateObject

Returns the value of attribute fields_to_validate.



146
147
148
# File 'lib/arkenstone/validation/validations.rb', line 146

def fields_to_validate
  @fields_to_validate
end

Class Method Details

.extended(base) ⇒ Object



141
142
143
# File 'lib/arkenstone/validation/validations.rb', line 141

def extended(base)
  base.fields_to_validate = {}
end

Instance Method Details

#create_validator(options_hash) ⇒ Object

Creates a validator hash from the options passed into a ‘validates` method.



184
185
186
187
188
189
# File 'lib/arkenstone/validation/validations.rb', line 184

def create_validator(options_hash)
  key = options_hash.first[0]
  validator = {}
  validator[key] = options_hash
  validator
end

#validate(custom_validation_method) ⇒ Object

Adds a custom validator method. Custom validators are responsible for adding errors to the ‘errors` hash. Example:

class MyClass
  validate :special_case

  def special_case
    if 1 == 2
      errors.add(:the_bad_property, "Error Message")
    end
  end
end


160
161
162
163
# File 'lib/arkenstone/validation/validations.rb', line 160

def validate(custom_validation_method)
  self.custom_validators = [] if custom_validators.nil?
  custom_validators << custom_validation_method
end

#validates(attr, *options) ⇒ Object

Adds one of the provided validators to an attribute. Specify the validator in the ‘options` splat. Example:

class MyClass

validates :name, presence: true
validates :email, with: format: { with: /[a-z]+/, message: "must be valid email" }

end



172
173
174
175
176
177
178
179
180
181
# File 'lib/arkenstone/validation/validations.rb', line 172

def validates(attr, *options)
  self.fields_to_validate = {} if fields_to_validate.nil?
  sym = attr.downcase.to_sym
  fields_for_attr = fields_to_validate[sym]
  if fields_for_attr.nil?
    fields_for_attr = []
    fields_to_validate[sym] = fields_for_attr
  end
  fields_for_attr << create_validator(Hash[*options])
end