Class: ClientSideValidations::Uniqueness

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

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Uniqueness

Returns a new instance of Uniqueness.



15
16
17
# File 'lib/client_side_validations.rb', line 15

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/client_side_validations.rb', line 19

def call(env)
  # By default CGI::parse will instantize a hash that defaults nil elements to [].
  # We need to override this
  case env['PATH_INFO']
  when %r{^/validations/uniqueness.json}
    params              = {}.merge!(CGI::parse(env['QUERY_STRING']))
    field               = params.keys.first
    resource, attribute = field.split(/[^\w]/)
    value               = params[field][0]
    # Because params returns an array for each field value we want to always grab
    # the first element of the array for id, even if it is nil
    id                  = [params["#{resource}[id]"]].flatten.first
    body                = is_unique?(resource, attribute, value, id).to_s
    [200, {'Content-Type' => 'application/json', 'Content-Length' => "#{body.length}"}, [body]]
  else
    @app.call(env)
  end
end