Class: HasFace::Validator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/has_face/validator.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Validator

Returns a new instance of Validator.



7
8
9
10
# File 'lib/has_face/validator.rb', line 7

def initialize(options)
  @allow_nil, @allow_blank = options.delete(:allow_nil), options.delete(:allow_blank)
  super
end

Instance Method Details

#validate_each(record, attr_name, value) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/has_face/validator.rb', line 12

def validate_each(record, attr_name, value)

  # Skip validation if globally turned off
  return if HasFace.enable_validation == false

  image       = record.send(attr_name)
  @image_path = image.respond_to?(:path) ? image.path : nil
  @image_url  = "#{ActionController::Base.asset_host}#{image.url if image.respond_to?(:url)}"

  # Skip validation if our image is nil/blank and allow nil/blank is on
  return if (@allow_nil && image.nil?) || (@allow_blank && image.blank?)

  # Add an error if the image path is blank
  return record.errors.add(attr_name, :no_face) if @image_path.blank?

  # Get the response and parse to JSON
  raw_response = RestClient.post(HasFace.detect_url, params)
  response     = JSON.parse(raw_response)

  # Error handling for failed responses
  return handle_api_error(response) unless response['status'] == 'success'

  # Add errors if no tags are present
  tags = response.try(:[], 'photos').try(:first).try(:[], 'tags')
  record.errors.add(attr_name, :no_face) if tags.blank?

rescue Errno::ECONNREFUSED, Errno::ETIMEDOUT, RestClient::Exception => error
  return handle_request_error(error)
end