f83c606bc7c3f5eded6333794ca48dc20b3e3925
[packages/precise/mcollective.git] / lib / mcollective / validator.rb
1 module MCollective
2   module Validator
3     @last_load = nil
4
5     # Loads the validator plugins. Validators will only be loaded every 5 minutes
6     def self.load_validators
7       if load_validators?
8         @last_load = Time.now.to_i
9         PluginManager.find_and_load("validator")
10       end
11     end
12
13     # Returns and instance of the Plugin class from which objects can be created.
14     # Valid plugin names are
15     #   :valplugin
16     #   "valplugin"
17     #   "ValpluginValidator"
18     def self.[](klass)
19       if klass.is_a?(Symbol)
20         klass = validator_class(klass)
21       elsif !(klass.match(/.*Validator$/))
22         klass = validator_class(klass)
23       end
24
25       const_get(klass)
26     end
27
28     # Allows validation plugins to be called like module methods : Validator.validate()
29     def self.method_missing(method, *args, &block)
30       if has_validator?(method)
31         validator = Validator[method].validate(*args)
32       else
33         raise ValidatorError, "Unknown validator: '#{method}'."
34       end
35     end
36
37     def self.has_validator?(validator)
38       const_defined?(validator_class(validator))
39     end
40
41     def self.validator_class(validator)
42       "#{validator.to_s.capitalize}Validator"
43     end
44
45     def self.load_validators?
46       return true if @last_load.nil?
47
48       (@last_load - Time.now.to_i) > 300
49     end
50
51     # Generic validate method that will call the correct validator
52     # plugin based on the type of the validation parameter
53     def self.validate(validator, validation)
54       Validator.load_validators
55
56       begin
57         if [:integer, :boolean, :float, :number, :string].include?(validation)
58           Validator.typecheck(validator, validation)
59
60         else
61           case validation
62             when Regexp,String
63               Validator.regex(validator, validation)
64
65             when Symbol
66               Validator.send(validation, validator)
67
68             when Array
69               Validator.array(validator, validation)
70
71             when Class
72               Validator.typecheck(validator, validation)
73           end
74         end
75       rescue => e
76         raise ValidatorError, e.to_s
77       end
78     end
79   end
80 end