Sha256: f3b2f7ae862a93fa72fb0f31ee8251cc0b7eb5dd768fdaf526845152ea1d8b27

Contents?: true

Size: 1.73 KB

Versions: 13

Compression:

Stored size: 1.73 KB

Contents

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

13 entries across 13 versions & 1 rubygems

Version Path
opt_parse_validator-0.0.17.0 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.16.6 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.16.5 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.16.4 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.16.3 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.16.2 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.16.1 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.16.0 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.15.2 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.15.1 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.15.0 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.14.1 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.14.0 lib/opt_parse_validator/opts/path.rb