lib/apidiesel/dsl.rb in apidiesel-0.1.1 vs lib/apidiesel/dsl.rb in apidiesel-0.1.2

- old
+ new

@@ -61,10 +61,11 @@ # # @param [Symbol] param_name name of the parameter # @param [Hash] *args # @option *args [Boolean] :optional (false) defines whether this parameter may be omitted # @option *args [Symbol] :optional_if_present param_name is optional, if the parameter given here is present instead + # @option *args [Symbol] :required_if_present param_name is required if param_name is also present # @option *args [Symbol] :submitted_as submit param_name to the API under the name given here # @option *args [Object] :default a default parameter to be set when no value is specified # @option *args [Enumerable] :allowed_values only accept the values in this Enumerable. # If Enumerable is a Hash, use the hash values to define what is actually # sent to the server. Example: `:allowed_values => {:foo => "f"}` allows @@ -99,10 +100,29 @@ # @option (see #string) def boolean(param_name, *args) validation_builder(:to_s, param_name, *args) end + # Defines a date, time or datetime parameter. + # + # + # @example + # expects do + # datetime :starts_at, format: '%d-%m-%Y' + # end + # + # @param (see #string) + # @option *args [String] :format strftime format string + # @option (see #string) + def datetime(param_name, **args) + if args[:format] + args[:processor] = ->(value) { value.try(:strftime, args[:format]) } + end + + validation_builder(:strftime, param_name, **args) + end + protected def validation_builder(duck_typing_check, param_name, *args) options = args.extract_options! @@ -113,10 +133,14 @@ if options.has_key?(:optional_if_present) options[:optional] = true unless given_params[ options[:optional_if_present] ].blank? end + if options.has_key?(:required_if_present) + options[:optional] = given_params[ options[:required_if_present] ].present? ? false : true + end + unless options.has_key?(:optional) && options[:optional] == true raise Apidiesel::InputError, "missing arg: #{param_name} - options: #{options.inspect}" unless given_params.has_key?(param_name) && !given_params[param_name].blank? raise Apidiesel::InputError, "invalid arg #{param_name}: must respond to #{duck_typing_check}" unless given_params[param_name].respond_to?(duck_typing_check) end @@ -126,9 +150,13 @@ end if options[:allowed_values].is_a? Hash given_params[param_name] = options[:allowed_values][ given_params[param_name] ] end + end + + if options[:processor] + given_params[param_name] = options[:processor].call(given_params[param_name]) end if options[:submitted_as] processed_params[ options[:submitted_as] ] = given_params[param_name] else \ No newline at end of file