class Alias::Validator

Creates validations for use with Alias::Creator.valid.

Attributes

validators[R]

Hash of registered validators.

message[R]
validation_proc[R]

Public Class Methods

default_validators() click to toggle source

Default validators are :constant, :class, :instance_method and :class_method.

# File lib/alias/validator.rb, line 66
def default_validators
  [
    {:key=>:constant, :if=>lambda {|e| any_const_get(e) }, :message=>lambda {|e| "Constant '#{e}' not created since it doesn't exist"}},
    {:key=>:class, :if=>lambda {|e| ((klass = any_const_get(e)) && klass.is_a?(Module)) },
      :message=>lambda {|e| "Alias for class '#{e}' not created since the class doesn't exist"}},
    {:key=>:instance_method, :if=> lambda {|e| instance_method?(*e) },
      :message=>lambda {|e| "Alias for instance method '#{e[0]}.#{e[1]}' not created since it doesn't exist" }},
    {:key=>:class_method, :if=>lambda {|e| class_method?(*e) },
      :message=>lambda {|e| "Alias for class method '#{e[0]}.#{e[1]}' not created since it doesn't exist" }}
  ]
end
new(options={}) click to toggle source

Options are described in Alias::Creator.valid.

# File lib/alias/validator.rb, line 9
def initialize(options={})
  raise ArgumentError unless options[:key] && options[:creator]
  @condition = options[:if] || options[:unless] || raise(MissingConditionError)
  inherits(Validator.validators[@condition]) if Validator.validators[@condition]
  raise InvalidValidatorError unless @condition.is_a?(Proc)
  @optional = options[:optional] || false
  @validation_proc = options[:unless] ? lambda {|e| ! @condition.clone.call(e) } : @condition
  @options = options
  @message = options[:message] if options[:message]
  @message = default_message unless @message.is_a?(Proc)
end
register_validators(validators) click to toggle source

Registers validators which creators can reference as symbols in Alias::Creator.valid.

# File lib/alias/validator.rb, line 58
def register_validators(validators)
  @validators ||= {}
  validators.each do |e|
    @validators[e[:key]] ||= Validator.new(e.merge(:creator=>self))
  end
end

Public Instance Methods

validate(current_creator, alias_hash, current_attribute) click to toggle source

Validates a given alias hash with the validator proc defined by :if or :unless in Alias::Creator.valid. Default arguments that these procs receive works as follows: If the validation key is the same name as any of the keys in the alias hash, then only the value of that that alias key is passed to the procs. If not, then the whole alias hash is passed.

# File lib/alias/validator.rb, line 25
def validate(current_creator, alias_hash, current_attribute)
  return true if @optional && current_creator.force
  arg = create_proc_arg(alias_hash, current_attribute)
  result = !!@validation_proc.call(arg)
  puts create_message(arg) if result != true && current_creator.verbose
  result
end