Module: Bodhi::Validations::ClassMethods

Defined in:
lib/bodhi-slam/validations.rb

Instance Method Summary collapse

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, options)
  unless attribute.is_a? Symbol
    raise ArgumentError.new("Invalid :attribute argument. Expected #{attribute.class} to be a Symbol")
  end
  
  unless options.is_a? Hash
    raise ArgumentError.new("Invalid :options argument. Expected #{options.class} to be a Hash")
  end
  
  if options.keys.empty?
    raise ArgumentError.new("Invalid :options argument. Options can not be empty")
  end

  options = options.reduce({}) do |memo, (k, v)| 
    memo.merge({ k.to_sym => v})
  end

  @validators[attribute] = []
  options.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, options[:ref])
      else
        @validators[attribute] << Bodhi::Validator.constantize(key).new(value)
      end
    end
  end
end

#validatorsObject

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