Module: SpatialFeatures::Validation

Defined in:
lib/spatial_features/validation.rb

Constant Summary collapse

REQUIRED_SHAPEFILE_COMPONENT_EXTENSIONS =
%w[shp shx dbf prj].freeze

Class Method Summary collapse

Class Method Details

.validate_shapefile!(shp_file, default_proj4_projection: nil) ⇒ Object

Check if a shapefile includes the required component files, otherwise raise an exception.

This validation operates by checking sibling files in the same directory, similar to how ‘rgeo-shapefile` validates SHP files.

Parameters:

  • shp_file (File)

    A File object

  • default_proj4_projection (String) (defaults to: nil)

    Optional, if supplied we don’t raise an exception when we’re missing a .PRJ file



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/spatial_features/validation.rb', line 14

def validate_shapefile!(shp_file, default_proj4_projection: nil)
  basename = File.basename(shp_file.path, '.*')
  path = shp_file.path.to_s.sub(/\.shp$/i, "")

  required_extensions = REQUIRED_SHAPEFILE_COMPONENT_EXTENSIONS
  required_extensions -= ['prj'] if default_proj4_projection

  required_extensions.each do |ext|
    component_path = "#{path}.#{ext}"
    next if ::File.file?(component_path) && ::File.readable?(component_path)

    case ext
      when "prj"
        raise ::SpatialFeatures::Importers::IndeterminateShapefileProjection, "Shapefile archive is missing a projection file: #{File.basename(component_path)}"
      else
        raise ::SpatialFeatures::Importers::IncompleteShapefileArchive, "Shapefile archive is missing a required file: #{File.basename(component_path)}"
      end
  end

  true
end

.validate_shapefile_archive!(path, default_proj4_projection: nil, allow_generic_zip_files: false) ⇒ Object

Validation helper that takes examines an entire ZIP file

Useful for validating before persisting records but not used internally



39
40
41
42
43
44
45
46
# File 'lib/spatial_features/validation.rb', line 39

def validate_shapefile_archive!(path, default_proj4_projection: nil, allow_generic_zip_files: false)
  Download.open_each(path, unzip: /\.shp$/, downcase: true).each do |shp_file|
    validate_shapefile!(shp_file, default_proj4_projection: default_proj4_projection)
  end
rescue Unzip::PathNotFound
  raise ::SpatialFeatures::Importers::IncompleteShapefileArchive, "Shapefile archive is missing a SHP file" \
    unless allow_generic_zip_files
end