Class: J2119::FieldValueConstraint

Inherits:
Constraint show all
Defined in:
lib/j2119/constraints.rb

Overview

Verify constraints on values of a named field

Instance Method Summary collapse

Methods inherited from Constraint

#add_condition, #applies

Constructor Details

#initialize(name, params) ⇒ FieldValueConstraint

Returns a new instance of FieldValueConstraint.



223
224
225
226
227
# File 'lib/j2119/constraints.rb', line 223

def initialize(name, params)
  super()
  @name = name
  @params = params
end

Instance Method Details

#check(node, path, problems) ⇒ Object



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/j2119/constraints.rb', line 234

def check(node, path, problems)

  # value-checking is orthogonal to existence checking
  return if !node.key?(@name)

  value = node[@name]

  if @params[:enum]
    if !(@params[:enum].include?(value))
      problems <<
        "#{path}.#{@name} is \"#{value}\", " +
        "not one of the allowed values #{@params[:enum]}"
    end
    
    # if enum constraint are provided, others are ignored
    return
  end

  if @params[:equal]
    begin
      if value != @params[:equal]
        problems <<
          "#{path}.#{@name} is #{value} " +
          "but required value is #{@params[:equal]}"
      end
    rescue Exception
      # should be caught by type constraint
    end
  end
  if @params[:floor]
    begin
      if value <= @params[:floor]
        problems <<
          "#{path}.#{@name} is #{value} " +
          "but allowed floor is #{@params[:floor]}"
      end
    rescue Exception
      # should be caught by type constraint
    end
  end
  if @params[:min]
    begin
      if value < @params[:min]
        problems <<
          "#{path}.#{@name} is #{value} " +
          "but allowed minimum is #{@params[:min]}"
      end
    rescue Exception
      # should be caught by type constraint
    end
  end
  if @params[:ceiling]
    begin
      if value >= @params[:ceiling]
        problems <<
          "#{path}.#{@name} is #{value} " +
          "but allowed ceiling is #{@params[:ceiling]}"
      end
    rescue Exception
      # should be caught by type constraint
    end
  end
  if @params[:max]
    begin
      if value > @params[:max]
        problems <<
          "#{path}.#{@name} is #{value} " +
          "but allowed maximum is #{@params[:max]}"
      end
    rescue Exception
      # should be caught by type constraint
    end
  end
end

#to_sObject



229
230
231
232
# File 'lib/j2119/constraints.rb', line 229

def to_s
  conds = (@conditions.empty?) ? '' : " #{@conditions.size} conditions"
  "<Field #{@name} has constraints #{@params}#{conds}>"
end