避免在Jekyll Ruby插件中重复调用API

时间:2013-03-05 22:02:37

标签: ruby api jekyll garb-gem

我编写了一个Jekyll插件,通过使用garb gem调用Google AnalyticsAPI来显示网页浏览量。我的方法唯一的麻烦是它为每个页面调用API,减慢了构建时间并且还可能达到API的用户调用限制。

可以在一次调用中返回所有数据并将其存储在本地,然后从每个页面查找页面浏览量,但我的Jekyll / Ruby-fu不是最新的。我不知道如何编写插件来运行一次以获取所有数据并将其存储在我当前函数可以访问它的本地,而不是逐页调用API。

基本上我的代码是作为一个可以放入我的页面布局的液体块写的:

 class GoogleAnalytics < Liquid::Block
    def initialize(tag_name, markup, tokens)
      super # options that appear in block (between tag and endtag)
      @options = markup # optional optionss passed in by opening tag
    end
    def render(context)
      path = super
      # Read in credentials and authenticate 
      cred = YAML.load_file("/home/cboettig/.garb_auth.yaml")
      Garb::Session.api_key = cred[:api_key]
      token = Garb::Session.login(cred[:username], cred[:password])
      profile = Garb::Management::Profile.all.detect {|p| p.web_property_id == cred[:ua]}

      # place query, customize to modify results
      data = Exits.results(profile, 
                           :filters => {:page_path.eql => path}, 
                           :start_date => Chronic.parse("2011-01-01"))

      data.first.pageviews
    end

Full version of my plugin is here

如何将所有对API的调用移动到其他函数并确保jekyll在开始时运行一次,然后调整上面的标记以读取本地数据?

编辑看起来可以使用Generator完成此操作并将数据写入文件。请参阅this branch上的示例现在我只需要弄清楚如何对结果进行分组:https://github.com/Sija/garb/issues/22

1 个答案:

答案 0 :(得分:0)

要存储数据,我必须:

  1. 编写一个Generator类(参见Jekyll wiki plugins)来调用API。

  2. 将数据转换为哈希值(以便按路径查找,参见5):

    result = Hash[data.collect{|row| [row.page_path, [row.exits, row.pageviews]]}]
    
  3. 将数据哈希写入JSON文件。

  4. 从我现有的Liquid block class中读取文件中的数据。

    请注意,块标记的工作原理来自_includes目录,而生成器的工作原理来自根目录。

  5. 匹配页面路径,一旦数据转换为哈希就很容易:

    result[path][1]
    
  6. Code for the full plugin, showing how to create the generator and write files, etc, here

    感谢GitHub上的Sija寻求帮助。

相关问题