class JsonTableSchema::Types::Base

Public Class Methods

new(field) click to toggle source
# File lib/jsontableschema/types/base.rb, line 7
def initialize(field)
  @field = field
  @constraints = field['constraints'] || {}
  @required = ['true', true].include?(@constraints['required'])
  @type = @field['type']
  set_format
end

Public Instance Methods

cast(value, skip_constraints = false) click to toggle source
# File lib/jsontableschema/types/base.rb, line 15
def cast(value, skip_constraints = false)
  JsonTableSchema::Constraints.new(@field, value).validate! unless skip_constraints
  return nil if is_null?(value)
  send("cast_#{@format}", value)
rescue NoMethodError => e
  if e.message.start_with?('undefined method `cast_')
    raise(JsonTableSchema::InvalidFormat.new("The format `#{@format}` is not supported by the type `#{@type}`"))
  else
    raise e
  end
end
set_format() click to toggle source
# File lib/jsontableschema/types/base.rb, line 34
def set_format
  if (@field['format'] || '').start_with?('fmt:')
    @format, @format_string = *@field['format'].split(':', 2)
  else
    @format = @field['format'] || 'default'
  end
end
test(value) click to toggle source
# File lib/jsontableschema/types/base.rb, line 27
def test(value)
  cast(value, true)
  true
rescue JsonTableSchema::Exception
  false
end

Private Instance Methods

is_null?(value) click to toggle source
# File lib/jsontableschema/types/base.rb, line 44
def is_null?(value)
  null_values.include?(value) && @required == false
end
null_values() click to toggle source
# File lib/jsontableschema/types/base.rb, line 48
def null_values
  ['null', 'none', 'nil', 'nan', '-', '']
end