Module: Bodhi::Validations::ClassMethods
- Defined in:
- lib/bodhi-slam/validations.rb
Instance Method Summary collapse
-
#validates(attribute, options) ⇒ Object
Creates a new validation on the given
attribute
using the suppliedoptions
. -
#validators ⇒ Object
Returns a Hash of all validations present for the class.
Instance Method Details
#validates(attribute, options) ⇒ Object
Creates a new validation on the given attribute
using the supplied options
class User
include Bodhi::Validations
attr_accessor :name, :address, :tags
validates :name, type: "String", required: true
validates :address, type: "PostalAddress", required: true
validates :tags, type: "String", multi: true
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/bodhi-slam/validations.rb', line 35 def validates(attribute, ) unless attribute.is_a? Symbol raise ArgumentError.new("Invalid :attribute argument. Expected #{attribute.class} to be a Symbol") end unless .is_a? Hash raise ArgumentError.new("Invalid :options argument. Expected #{.class} to be a Hash") end if .keys.empty? raise ArgumentError.new("Invalid :options argument. Options can not be empty") end = .reduce({}) do |memo, (k, v)| memo.merge({ k.to_sym => v}) end @validators[attribute] = [] .each_pair do |key, value| key = key.to_s.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').gsub(/([a-z\d])([A-Z])/,'\1_\2').tr("-", "_").downcase.to_sym unless [:ref].include?(key) if key == :type && value == "Enumerated" @validators[attribute] << Bodhi::Validator.constantize(key).new(value, [:ref]) else @validators[attribute] << Bodhi::Validator.constantize(key).new(value) end end end end |
#validators ⇒ Object
Returns a Hash of all validations present for the class
class User
include Bodhi::Validations
attr_accessor :name, :tags
validates :tags, requried: true, multi: true
validates :name, required: true
User.validations # => {
tags: [
#<RequiredValidator:0x007fbff403e808 @options={}>,
#<MultiValidator:0x007fbff403e808 @options={}>
],
name: [
#<RequiredValidator:0x007fbff403e808 @options={}>
]
}
24 |
# File 'lib/bodhi-slam/validations.rb', line 24 def validators; @validators; end |