Sha256: 7777b8741e0a536357832bf84ea5a8743c6a4f32987f6a5004ed81e76a29d959

Contents?: true

Size: 1.76 KB

Versions: 9

Compression:

Stored size: 1.76 KB

Contents

# frozen_string_literal: true

module OptParseValidator
  # Implementation of the Path Option
  class OptPath < OptBase
    # Initialize attrs:
    #
    # :create     if set to true, will create the path
    #
    # :exists     if set to false, will ignore the file? and directory? checks
    #
    # :file       Check if the path is a file
    # :directory  Check if the path is a directory
    #
    # :executable
    # :readable
    # :writable
    #

    # @param [ String ] value
    #
    # @return [ String ]
    def validate(value)
      path = Pathname.new(value)

      allowed_attrs.each do |key|
        method = "check_#{key}"
        send(method, path) if respond_to?(method) && attrs[key]
      end

      path.to_s
    end

    def allowed_attrs
      %i[create file directory executable readable writable]
    end

    # check_create is implemented in the file_path and directory_path opts

    # @param [ Pathname ] path
    def check_file(path)
      raise Error, "'#{path}' is not a file" unless path.file? || attrs[:exists] == false
    end

    # @param [ Pathname ] path
    def check_directory(path)
      raise Error, "'#{path}' is not a directory" unless path.directory? || attrs[:exists] == false
    end

    # @param [ Pathname ] path
    def check_executable(path)
      raise Error, "'#{path}' is not executable" unless path.executable?
    end

    # @param [ Pathname ] path
    def check_readable(path)
      raise Error, "'#{path}' is not readable" unless path.readable?
    end

    # If the path does not exist, it will check for the parent
    # directory write permission
    #
    # @param [ Pathname ] path
    def check_writable(path)
      raise Error, "'#{path}' is not writable" if path.exist? && !path.writable? || !path.parent.writable?
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
opt_parse_validator-1.9.1 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-1.9.0 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-1.8.2 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-1.8.1 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-1.8.0 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-1.7.4 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-1.7.3 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-1.7.2 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.17.1 lib/opt_parse_validator/opts/path.rb