Sha256: 09fcc94f660f33269f71af4a76195eb060f17c3a27b608cec99d745d0a5cadb0

Contents?: true

Size: 1.56 KB

Versions: 10

Compression:

Stored size: 1.56 KB

Contents

module OptParseValidator
  # Implementation of the Path Option
  class OptPath < OptBase
    # Initialize attrs:
    #
    # :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 self.respond_to?(method) && attrs[key]
      end

      path.to_s
    end

    def allowed_attrs
      [:file, :directory, :executable, :readable, :writable]
    end

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

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

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

    # @param [ Pathname ] path
    def check_readable(path)
      fail "'#{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)
      fail "'#{path}' is not writable" if path.exist? && !path.writable? || !path.parent.writable?
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
opt_parse_validator-0.0.11 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.10 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.9 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.8 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.7 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.6 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.5 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.4 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.3 lib/opt_parse_validator/opts/path.rb
opt_parse_validator-0.0.2 lib/opt_parse_validator/opts/path.rb