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
35
36
37
38
39
40
41
# 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)

    # A shapefile is a set of files that must travel together, and an export that
    # drops one is the single most common thing wrong with an upload. Name the
    # missing part and the way out, rather than only the file we couldn't find.
    case ext
      when "prj"
        raise ::SpatialFeatures::Importers::IndeterminateShapefileProjection,
              "This shapefile has no projection file — #{File.basename(component_path)} is missing, " \
              "so there is no way to tell where on the earth it belongs. Re-export it with the projection included."
      else
        raise ::SpatialFeatures::Importers::IncompleteShapefileArchive,
              "This shapefile is incomplete — #{File.basename(component_path)} is missing. " \
              "A shapefile is a set of files that have to be zipped up together: .shp, .shx, .dbf and .prj."
      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



46
47
48
49
50
51
52
53
# File 'lib/spatial_features/validation.rb', line 46

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, "This archive has no shapefile (.shp) in it." \
    unless allow_generic_zip_files
end