代码之家  ›  专栏  ›  技术社区  ›  Picachieu

如何在ruby中获得文件模式?

  •  1
  • Picachieu  · 技术社区  · 7 年前

    我刚接触ruby文件IO。我有一个函数需要 File 参数,我需要确保文件处于只读模式。

    def myfunction(file)
        raise ArgumentError.new() unless file.kind_of?(File)
    
        #Assert that file is in read-only mode
    end
    

    任何帮助都将不胜感激!

    3 回复  |  直到 7 年前
        1
  •  0
  •   Picachieu    7 年前

    你可以用 file.readable? ,返回true或false。

    请检查 this link.

        2
  •  2
  •   Andrew Schwartz    7 年前

    reopen ,我想是这样的:

    file = file.reopen(file.path, "r")

    我找不到其他方法来验证是否存在写流,但这里有一个小技巧可以奏效。虽然我不喜欢在预期的路径中使用异常抛出,但是您可以使用 close_write :

    begin
      file.close_write
      # you could actually raise an exception here if you want
      # since getting here means the file was originally opened for writing
    rescue IOError
      # This error will be raised if the file was not opened for
      # writing, so this is actually the path we want
    end
    
        3
  •  2
  •   Galaxy    7 年前

    FileUtils.chmod .

    File.writeable

    推荐文章