lib/apipie/validator.rb in apipie-rails-0.0.17 vs lib/apipie/validator.rb in apipie-rails-0.0.18

- old
+ new

@@ -64,10 +64,14 @@ # thor supported types :string, :hash, :array, :numeric, or :boolean def expected_type 'string' end + def merge_with(other_validator) + raise NotImplementedError, "Dont know how to merge #{self.inspect} with #{other_validator.inspect}" + end + end # validate arguments type class TypeValidator < BaseValidator @@ -167,26 +171,39 @@ "" end end class HashValidator < BaseValidator + include Apipie::DSL::Base + include Apipie::DSL::Param - attr_reader :hash_params_ordered - def self.build(param_description, argument, options, block) - self.new(param_description, block) if block.is_a?(Proc) && block.arity <= 0 && argument == Hash + self.new(param_description, block, options[:param_group]) if block.is_a?(Proc) && block.arity <= 0 && argument == Hash end - def initialize(param_description, argument) + def initialize(param_description, argument, param_group) super(param_description) @proc = argument - @hash_params_ordered = [] - @hash_params = {} - + @param_group = param_group self.instance_exec(&@proc) + # specifying action_aware on Hash influences the child params, + # not the hash param itself: assuming it's required when + # updating as well + if param_description.options[:action_aware] && param_description.options[:required] + param_description.required = true + end + prepare_hash_params end + def hash_params_ordered + @hash_params_ordered ||= _apipie_dsl_data[:params].map do |args| + options = args.find { |arg| arg.is_a? Hash } + options[:parent] = self.param_description + Apipie::ParamDescription.from_dsl_data(param_description.method_description, args) + end + end + def validate(value) if @hash_params @hash_params.each do |k, p| p.validate(value[k]) if value.has_key?(k) || p.required end @@ -196,18 +213,32 @@ def description "Must be a Hash" end - def param(param_name, validator, desc_or_options = nil, options = {}, &block) - param_description = Apipie::ParamDescription.new(param_name, validator, desc_or_options, options, &block) - param_description.parent = self.param_description - @hash_params_ordered << param_description - @hash_params[param_name.to_sym] = param_description - end - def expected_type 'hash' + end + + # where the group definition should be looked up when no scope + # given. This is expected to return a controller. + def _default_param_group_scope + @param_group && @param_group[:scope] + end + + def merge_with(other_validator) + if other_validator.is_a? HashValidator + @hash_params_ordered = ParamDescription.unify(self.hash_params_ordered + other_validator.hash_params_ordered) + prepare_hash_params + else + super + end + end + + def prepare_hash_params + @hash_params = hash_params_ordered.reduce({}) do |h, param| + h.update(param.name.to_sym => param) + end end end # special type of validator: we say that it's not specified