Module: Goliath::Rack::Validation::Coerce

Included in:
Param
Defined in:
lib/goliath/rack/validation/coerce.rb

Constant Summary collapse

NOT_CLASS_ERROR =
"Params as must be a class"
INVALID_COERCE_TYPE =
"%s does not respond to coerce"

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/goliath/rack/validation/coerce.rb', line 29

def call(env)
  begin
    coerce_value(env['params']) if @coerce_instance
    nil
  rescue FailedCoerce => e
    return e.error unless @optional
  end
  super if defined?(super)
end

#coerce_setup!(opts = {}) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/goliath/rack/validation/coerce.rb', line 16

def coerce_setup!(opts={})
  as = opts.delete(:as)
  if as
    unless Class === as
      raise Exception.new(NOT_CLASS_ERROR)
    end
    @coerce_instance = as.new
    unless @coerce_instance.respond_to?(:coerce)
      raise Exception.new(INVALID_COERCE_TYPE % @coerce_instance)
    end
  end
end

#coerce_value(params) ⇒ Object



39
40
41
42
43
44
# File 'lib/goliath/rack/validation/coerce.rb', line 39

def coerce_value(params)
  opts = {:default => @default, :message => @message}
  value_before_coerce = fetch_key(params)
  value_after_coerce = @coerce_instance.coerce(value_before_coerce, opts)
  fetch_key(params, value_after_coerce)
end