Class: TableSchema::Field

Inherits:
Hash
  • Object
show all
Includes:
Helpers
Defined in:
lib/tableschema/field.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helpers

#deep_symbolize_keys, #get_class_for_type, #type_class_lookup

Constructor Details

#initialize(descriptor, missing_values = nil) ⇒ Field

Returns a new instance of Field.



11
12
13
14
15
16
17
18
19
# File 'lib/tableschema/field.rb', line 11

def initialize(descriptor, missing_values=nil)
  self.merge! deep_symbolize_keys(descriptor)
  @name = self[:name]
  @type = self[:type] = self.fetch(:type, TableSchema::DEFAULTS[:type])
  @format = self[:format] = self.fetch(:format, TableSchema::DEFAULTS[:format])
  @constraints = self[:constraints] = self.fetch(:constraints, {})
  @required = @constraints.fetch(:required, false)
  @missing_values = missing_values || default_missing_values
end

Instance Attribute Details

#constraintsObject (readonly)

Public



9
10
11
# File 'lib/tableschema/field.rb', line 9

def constraints
  @constraints
end

#formatObject (readonly)

Public



9
10
11
# File 'lib/tableschema/field.rb', line 9

def format
  @format
end

#nameObject (readonly)

Public



9
10
11
# File 'lib/tableschema/field.rb', line 9

def name
  @name
end

#requiredObject (readonly)

Public



9
10
11
# File 'lib/tableschema/field.rb', line 9

def required
  @required
end

#typeObject (readonly)

Public



9
10
11
# File 'lib/tableschema/field.rb', line 9

def type
  @type
end

Instance Method Details

#cast_type(value) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/tableschema/field.rb', line 39

def cast_type(value)
  if is_null?(value)
    nil
  else
    type_class.new(self).cast(value)
  end
end

#cast_value(value, constraints: true) ⇒ Object



25
26
27
28
29
30
# File 'lib/tableschema/field.rb', line 25

def cast_value(value, constraints: true)
  cast_value = cast_type(value)
  return cast_value if constraints == false
  TableSchema::Constraints.new(self, cast_value).validate!
  cast_value
end

#descriptorObject



21
22
23
# File 'lib/tableschema/field.rb', line 21

def descriptor
  self.to_h
end

#test_value(value, constraints: true) ⇒ Object



32
33
34
35
36
37
# File 'lib/tableschema/field.rb', line 32

def test_value(value, constraints: true)
  cast_value(value, constraints: constraints)
  true
rescue TableSchema::Exception
  false
end