Class: ValidatorCache

Inherits:
Object
  • Object
show all
Defined in:
common/validator_cache.rb

Class Method Summary collapse

Class Method Details

.create_validator(jsonmodel, data) ⇒ Object



3
4
5
6
7
8
# File 'common/validator_cache.rb', line 3

def self.create_validator(jsonmodel, data)
  JSON::Validator.new(jsonmodel.schema,
                      data,
                      :errors_as_objects => true,
                      :record_errors => true)
end

.with_validator_for(jsonmodel, data) ⇒ Object



10
11
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
41
42
43
44
45
# File 'common/validator_cache.rb', line 10

def self.with_validator_for(jsonmodel, data)
  Thread.current[:validator_cache] ||= {}

  created = false
  if Thread.current[:validator_cache][jsonmodel]

    # If we have a cache entry but it's in use, just return a newly allocated
    # validator.
    if Thread.current[:validator_cache][jsonmodel][:in_use]
      return self.create_validator(jsonmodel, data)
    end

  else
    # If there's no entry, add one
    Thread.current[:validator_cache][jsonmodel] = {}
    Thread.current[:validator_cache][jsonmodel][:validator] = self.create_validator(jsonmodel, data)
    created = true
  end

  validator = Thread.current[:validator_cache][jsonmodel][:validator]

  # Reuse this existing validator by setting its data
  if !created
    validator.instance_eval do
      @data = data
    end
  end

  Thread.current[:validator_cache][jsonmodel][:in_use] = true

  begin
    yield(validator)
  ensure
    Thread.current[:validator_cache][jsonmodel][:in_use] = false
  end
end