module Bodhi::Validations::ClassMethods

Public Instance Methods

validates(attribute, options) click to toggle source

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
# 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
validators() click to toggle source

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={}>
  ]
}
# File lib/bodhi-slam/validations.rb, line 24
def validators; @validators; end