Module: Sinatra::Param

Defined in:
lib/sinatra/param.rb,
lib/sinatra/param/version.rb

Defined Under Namespace

Classes: InvalidParameterError

Constant Summary collapse

Boolean =
:boolean
VERSION =
'1.3.1'

Instance Method Summary collapse

Instance Method Details

#one_of(*args) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/sinatra/param.rb', line 39

def one_of(*args)
  options = args.last.is_a?(Hash) ? args.pop : {}
  names = args.collect(&:to_s)

  return unless names.length >= 2

  begin
    validate_one_of!(params, names, options)
  rescue InvalidParameterError => exception
    if options[:raise] or (settings.raise_sinatra_param_exceptions rescue false)
      exception.param, exception.options = names, options
      raise exception
    end

    error = "Parameters #{names.join(', ')} are mutually exclusive"
    if content_type and content_type.match(mime_type(:json))
      error = {message: error, errors: {names => exception.message}}.to_json
    end

    halt 400, error
  end
end

#param(name, type, options = {}) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/sinatra/param.rb', line 14

def param(name, type, options = {})
  name = name.to_s

  return unless params.member?(name) or options[:default] or options[:required]

  begin
    params[name] = coerce(params[name], type, options)
    params[name] = (options[:default].call if options[:default].respond_to?(:call)) || options[:default] if params[name].nil? and options[:default]
    params[name] = options[:transform].to_proc.call(params[name]) if params[name] and options[:transform]
    validate!(params[name], options)
  rescue InvalidParameterError => exception
    if options[:raise] or (settings.raise_sinatra_param_exceptions rescue false)
      exception.param, exception.options = name, options
      raise exception
    end

    error = "Invalid Parameter: #{name}"
    if content_type and content_type.match(mime_type(:json))
      error = {message: error, errors: {name => exception.message}}.to_json
    end

    halt 400, error
  end
end