Class: Goliath::Rack::Validation::DefaultParams

Inherits:
Object
  • Object
show all
Defined in:
lib/goliath/rack/validation/default_params.rb

Overview

A middleware to validate that a parameter always has a value

Examples:

use Goliath::Rack::Validation::DefaultParams, {:key => 'order', :defaults => 'pubdate'}

Instance Method Summary (collapse)

Constructor Details

- (Goliath::Rack::Validation::DefaultParams) initialize(app, opts = {})

Called by the framework to create the validator

Parameters:

  • app

    The app object

  • (Hash) opts (defaults to: {})

    The options hash

Options Hash (opts):

  • (String) :key

    The key to access in the parameters

  • (Object) :defaults

    The default value to assign if the key is empty or non-existant

Raises:

  • (Exception)


19
20
21
22
23
24
25
26
# File 'lib/goliath/rack/validation/default_params.rb', line 19

def initialize(app, opts = {})
  @app = app
  @defaults = opts[:defaults]
  raise Exception.new("Must provide defaults to DefaultParams") if @defaults.nil?

  @key = opts[:key]
  raise Exception.new("must provide key to DefaultParams") if @key.nil? || @key =~ /^\s*$/
end

Instance Method Details

- (Object) call(env)



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/goliath/rack/validation/default_params.rb', line 28

def call(env)
  if !env['params'].has_key?(@key) || env['params'][@key].nil?
    env['params'][@key] = @defaults

  elsif env['params'][@key].is_a?(Array) && env['params'][@key].empty?
    env['params'][@key] = @defaults

  elsif env['params'][@key].is_a?(String)
    if env['params'][@key] =~ /^\s*$/
      env['params'][@key] = @defaults
    end
  end

  @app.call(env)
end