Class: Sinatra::ParamChecker::ParamScope
- Inherits:
-
Object
- Object
- Sinatra::ParamChecker::ParamScope
- Defined in:
- lib/sinatra/param_checker.rb
Instance Attribute Summary collapse
-
#params ⇒ Object
readonly
Returns the value of attribute params.
Instance Method Summary collapse
-
#initialize ⇒ ParamScope
constructor
A new instance of ParamScope.
- #optional(name, options = {}) ⇒ Object
- #required(name, options = {}) ⇒ Object
- #validate!(params) ⇒ Object
Constructor Details
#initialize ⇒ ParamScope
Returns a new instance of ParamScope.
12 13 14 |
# File 'lib/sinatra/param_checker.rb', line 12 def initialize @params = [] end |
Instance Attribute Details
#params ⇒ Object (readonly)
Returns the value of attribute params.
11 12 13 |
# File 'lib/sinatra/param_checker.rb', line 11 def params @params end |
Instance Method Details
#optional(name, options = {}) ⇒ Object
22 23 24 25 26 |
# File 'lib/sinatra/param_checker.rb', line 22 def optional(name, = {}) param = [:optional, name.to_s, ] validate_opts! param @params << param end |
#required(name, options = {}) ⇒ Object
16 17 18 19 20 |
# File 'lib/sinatra/param_checker.rb', line 16 def required(name, = {}) param = [:required, name.to_s, ] validate_opts! param @params << param end |
#validate!(params) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/sinatra/param_checker.rb', line 28 def validate!(params) validated_params = @params.reduce({}) do |memo, e| type, name, opts = e begin # handle default v = if params[name].nil? case type when :optional (opts[:default].call if opts[:default].respond_to?(:call)) || opts[:default] when :required raise InvalidParameterError, "param #{name} not found" end else params[name] end unless v.nil? coerced_value = coerce(v, opts[:type], opts) validate(coerced_value, opts) memo[name] = coerced_value end memo rescue InvalidParameterError => e e.param, e. = name, opts raise e end end validated_params.reduce(params) do |memo, pair| k, v = pair memo[k] = v memo end end |