知道文件是否是YAML

时间:2017-06-15 18:12:26

标签: ruby yaml

如果server { listen 80 default_server; listen [::]:80 default_server; root /var/www/wordpress; index index.php index.html; location = /favicon.ico { log_not_found off; access_log off; } location = /robots.txt { allow all; log_not_found off; access_log off; } location ~ /\. { deny all; } location ~* /(?:uploads|files)/.*\.php$ { deny all; } location / { try_files $uri $uri/ /index.php?$args; } rewrite /wp-admin$ $scheme://$host$uri/ permanent; location ~ \.php$ { include /etc/nginx/fastcgi_params; fastcgi_pass php:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name; } } 不是YAML文件,我希望YAML.load_file(foo)的ruby YAML module返回null。但我得到例外:

foo

如果文件是YAML文件,如何在没有例外的情况下进行分类?在我的情况下,我导航到一个目录并处理markdown文件:我使用键did not find expected alphabetic or numeric character while scanning an alias at line 3 column 3 (Psych::SyntaxError) from /usr/lib/ruby/2.4.0/psych.rb:377:in `parse_stream' from /usr/lib/ruby/2.4.0/psych.rb:325:in `parse' from /usr/lib/ruby/2.4.0/psych.rb:252:in `load' from /usr/lib/ruby/2.4.0/psych.rb:473:in `block in load_file' from /usr/lib/ruby/2.4.0/psych.rb:472:in `open' from /usr/lib/ruby/2.4.0/psych.rb:472:in `load_file' from ./select.rb:27:in `block in selecting' from ./select.rb:26:in `each' from ./select.rb:26:in `selecting' from ./select.rb:47:in `block (2 levels) in <main>' from ./select.rb:46:in `each' from ./select.rb:46:in `block in <main>' from ./select.rb:44:in `each' from ./select.rb:44:in `<main>' 添加到列表markdown文件并返回该列表

output: word

当我捕获异常时,bucle不会继续推送列表中的元素。

2 个答案:

答案 0 :(得分:2)

Psych::SyntaxErrorPsych::Parser#parse引发,其源代码用C语言编写。因此,除非您想使用C,否则无法在Ruby中为该方法编写补丁以防止被提出的例外。

但是,你当然可以拯救这个例外,如下:

begin
  foo = YAML.load_file("not_yaml.txt")
rescue Psych::SyntaxError => error
  puts "bad yaml"
end

答案 1 :(得分:2)

简短的回答:你不能。

因为YAML只是一个文本文件,所以知道给定文本文件是否为YAML的唯一方法是解析它。解析器将尝试解析该文件,如果它不是有效的YAML,则会引发错误。

错误和异常是Ruby的常见部分,尤其是在IO世界中。没有理由害怕他们。您可以轻松地从他们身上拯救并继续前进:

begin
  yaml = YAML.load_file(foo)
rescue Psych::SyntaxError => e
  # handle the bad YAML here
end

您提到以下代码无效,因为您需要处理目录中的多个文件:

def foo
  mylist = []
  for d in (directory - excludinglist)
    begin
      info = YAML.load_file(d)
      if info
        if info.has_key?('output')
          if info['output'].has_key?(word)
            mylist.push(d)
          end 
        end
      end 
    rescue Psych::SyntaxError => error 
      return [] 
    end 
  return mylist
end

这里唯一的问题是,当您遇到错误时,您会通过提前返回来回复。如果您不返回,for循环将继续,您将获得所需的功能:

def foo
  mylist = []
  for d in (directory - excludinglist)
    begin
      info = YAML.load_file(d)
      if info
        if info.has_key?('output')
          if info['output'].has_key?(word)
            mylist.push(d)
          end 
        end
      end 
    rescue Psych::SyntaxError => error 
      # do nothing!
      # puts "or your could display an error message!"
    end
  end
  return mylist
end