为什么这个Jekyll插件会引发异常?

时间:2019-01-08 17:50:13

标签: ruby jekyll liquid jekyll-extensions

我有一个Jekyll网站,需要在其中显示该网站中各种文件的来源。为此,我尝试在模板中使用{% include filename %}。但是,事实证明,Liquid标签include仅接受_includes下的路径。最初,我将项目根目录链接到_includes下的路径。这可行,但是由于Jekyll花费了相当长的时间才能确定项目中存在无限递归的符号链接,因此构建过程确实很慢。

现在,我认为一种更好的方法是编写一个插件来制作一个full_include标签,该标签将接受相对于项目基础目录的任何路径。这是代码:

#!/usr/bin/env ruby

module MyIncludes

  class FullIncludeTag < Liquid::Tag
    def initialize(tag_name, filename, other)
      super
      $stderr.puts "===DEBUG=== Plugin FullIncludeTag initialized. Arguments:\n\ttag_name:\t#{tag_name}\n\tfilename:\t#{filename}\n\tother:\t#{other}"
      items = Dir.children(Dir.pwd)
      unless items.include?('_config.yml') and items.include('_includes')
        raise RuntimeError, "The working directory doesn't appear to be Jekyll's base directory!"
      end
      @filename = "#{Dir.pwd}/#{filename}"
    end

    def render(context)
      $stderr.puts "===DEBUG=== Plugin FullIncludeTag render beginning.\n\tcontext:\t#{context}\n\tfilename:\t#{@filename}"

      # The following two lines produce the exact same output the first time the plugin is called.
      $stderr.puts "#{Dir.pwd}/resume/portfolio_entries/raw/dice.py"
      $stderr.puts @filename

#       File.open "#{Dir.pwd}/resume/portfolio_entries/raw/dice.py" do |f|
#         return f.read
#       end
      File.open @filename do |f|
        return f.read.chomp
      end
    end
  end
end

Liquid::Template.register_tag('full_include', MyIncludes::FullIncludeTag)

我编写Ruby已有很多年了,我的Ruby技能令人难以置信的生锈,但是我似乎在这里找不到问题。这是正在发生的事情:

  1. 使用所示的代码,Jekyll产生以下输出:

    ===DEBUG=== Plugin FullIncludeTag render beginning.
            context:        #<Liquid::Context:0x018ee008>
            filename:       /home/scott/Main Sync/websites/scottseverance.mss/resume/portfolio_entries/raw/dice.py 
    /home/scott/Main Sync/websites/scottseverance.mss/resume/portfolio_entries/raw/dice.py
    /home/scott/Main Sync/websites/scottseverance.mss/resume/portfolio_entries/raw/dice.py 
      Liquid Exception: No such file or directory @ rb_sysopen - /home/scott/Main Sync/websites/scottseverance.mss/resume/portfolio_entries/raw/dice.py in resume/portfolio_entries/dice.html
    jekyll 3.8.4 | Error:  No such file or directory @ rb_sysopen - /home/scott/Main Sync/websites/scottseverance.mss/resume/portfolio_entries/raw/dice.py 
    
  2. 如果我切换注释掉哪个File.open块,那么例外就会消失。当然,由于路径是硬编码的,所以我第一次使用{% full_include %}时只会得到正确的内容,但这是可以预期的。

请特别注意,在代码注释中突出显示的两个$stderr.puts调用在任一变体中都产生相同的输出(至少对于使用硬编码路径调用的液体标记而言)。因此,我无法想到一个呼叫为什么有效而另一个呼叫失败的原因。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

我唯一想到的是@filename的末尾有空格。