Class: ParamSanitizer::RequestSanitizer

Inherits:
Object
  • Object
show all
Defined in:
lib/param_sanitizer/request_sanitizer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, *args) ⇒ RequestSanitizer

Returns a new instance of RequestSanitizer.



7
8
9
10
11
# File 'lib/param_sanitizer/request_sanitizer.rb', line 7

def initialize(app, *args)
  @app = app
  @strategized_routes = args.last.is_a?(Hash) ? args.last : {}
  emit_warning if @strategized_routes.empty?
end

Instance Attribute Details

#strategized_routesObject (readonly)

Returns the value of attribute strategized_routes.



5
6
7
# File 'lib/param_sanitizer/request_sanitizer.rb', line 5

def strategized_routes
  @strategized_routes
end

Instance Method Details

#build(strategy) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/param_sanitizer/request_sanitizer.rb', line 41

def build(strategy)
  if strategy.respond_to?(:call) then strategy
  elsif strategy.respond_to?(:new) then strategy.new
  elsif strategy.is_a?(Symbol) then ParamSanitizer::Strategies.const_get("#{strategy}Strategy").new
  else raise ArgumentError.new "#{strategy.to_s} does not support 'call'!"
  end
end

#call(env) ⇒ Object



13
14
15
16
17
18
# File 'lib/param_sanitizer/request_sanitizer.rb', line 13

def call(env)
  request = Rack::Request.new(env)
  request = execute_strategies(request) if has_strategy?(request.path)
  env["QUERY_STRING"] = encode_to_query_string(request.params)
  @app.call(env)
end

#emit_warningObject



33
34
35
# File 'lib/param_sanitizer/request_sanitizer.rb', line 33

def emit_warning
  puts "ParamSanitizer::RequestSanitizer initialized without sanitization strategies. Middleware is now a no-op"
end

#encode_to_query_string(params) ⇒ Object



37
38
39
# File 'lib/param_sanitizer/request_sanitizer.rb', line 37

def encode_to_query_string(params)
  URI.encode(params.map{|k,v| "#{k}=#{v}"}.join('&'))
end

#execute_strategies(request) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/param_sanitizer/request_sanitizer.rb', line 20

def execute_strategies(request)
  strategies = @strategized_routes[request.path]
  strategies.each { |strategy|
    instance = build(strategy)
    instance.call(request) if instance.respond_to? :call
  }
  request
end

#has_strategy?(route) ⇒ Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/param_sanitizer/request_sanitizer.rb', line 29

def has_strategy?(route)
  @strategized_routes.has_key?(route)
end