Class: Goliath::Rack::Validation::BooleanValue

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

Overview

A middleware to validate a given value is boolean. This will attempt to do the following conversions:

 true  = 'true'  | 't' | 1
 false = 'false' | 'f' | 0

If the parameter is not provided the :default is used.

Examples:

use Goliath::Rack::Validation::BooleanValue, {:key => 'raw', :default => false}

Instance Method Summary (collapse)

Constructor Details

- (Goliath::Rack::Validation::BooleanValue) 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

  • (Boolean) :default

    The default value to set

Raises:

  • (Exception)


22
23
24
25
26
27
28
# File 'lib/goliath/rack/validation/boolean_value.rb', line 22

def initialize(app, opts = {})
  @app = app
  @key = opts[:key]
  raise Exception.new("BooleanValue key required") if @key.nil?

  @default = opts[:default]
end

Instance Method Details

- (Object) call(env)



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
# File 'lib/goliath/rack/validation/boolean_value.rb', line 30

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

  else
    if env['params'][@key].instance_of?(Array)
      env['params'][@key] = env['params'][@key].first
    end

    if env['params'][@key].downcase == 'true' ||
        env['params'][@key].downcase == 't' ||
        env['params'][@key].to_i == 1
      env['params'][@key] = true

    elsif env['params'][@key].downcase == 'false' ||
        env['params'][@key].downcase == 'f' ||
        env['params'][@key].to_i == 0
      env['params'][@key] = false

    else
      env['params'][@key] = @default
    end
  end

  @app.call(env)
end