class ParamValidator::Base

Attributes

params[R]

Public Class Methods

inherited( base ) click to toggle source
Calls superclass method
# File lib/param_validator/base.rb, line 13
def self.inherited( base )
  self.specification = {}
  super
end
new( params ) click to toggle source
# File lib/param_validator/base.rb, line 9
def initialize( params )
  @params = params
end
validate( param, spec ) click to toggle source
# File lib/param_validator/base.rb, line 39
def self.validate( param, spec )
  self.specification = specification.merge( param => spec )
end

Public Instance Methods

errors() click to toggle source
# File lib/param_validator/base.rb, line 29
def errors
  @errors ||= []
end
full_errors() click to toggle source
# File lib/param_validator/base.rb, line 33
def full_errors
  errors.map do |param_and_msg|
    param_and_msg.join( ' ' )
  end
end
valid?() click to toggle source
# File lib/param_validator/base.rb, line 18
def valid?
  self.class.specification.each do |param, spec|
    value = fetch_parameter( param )
    if spec[:required] && (value.nil? || value.empty?)
      errors << [param, 'must be present']
    end
  end

  errors.empty?
end

Private Instance Methods

fetch_parameter( path ) click to toggle source
# File lib/param_validator/base.rb, line 45
def fetch_parameter( path )
  path( params, path )
end
parse_element__(elm_string) click to toggle source
# File lib/param_validator/base.rb, line 68
def parse_element__(elm_string)
  if elm_string =~ /^(.+)\[(\d+)\]$/
    [$1.to_sym, $2.to_i]
  elsif elm_string =~ /^(.+)_(\d+)$/
    [$1.to_sym, $2.to_i]
  else
    [elm_string.to_sym, nil]
  end
end
path( hash, *pathes ) click to toggle source
# File lib/param_validator/base.rb, line 49
def path( hash, *pathes )
  target = hash
  pathes.map! do |p|
    p.to_s.split(/[\/\.]+/)
  end
  pathes.flatten.each do |element|
    next if (element == nil || element == '')
    key, index = parse_element__(element)
    target = target[key] || target[key.to_s]
    return nil unless target
    if index
      raise "target=#{target.inspect} is not array. but specified index value." unless target.is_a?(Array)
      target = target[index]
      return nil unless target
    end
  end
  target
end