如何使用Middleman显示Gravtar?

时间:2014-01-07 22:03:07

标签: ruby gem middleman gravatar

我正在尝试构建我的第一个使用Middleman Frontmatter来显示Gravatar图像的ruby gem。

我的目标是使用这样的frontmatter作为输入

---
email: example@mail.com
---

...和输出 .erb文件中关联的Gravatar图像,如下所示:

<%= gravatar_for(article.data.email) %>

根据Gravatar提供的有关通过ruby显示图像的说明,我提出了以下内容:

require "gravatar/version"
require 'digest/md5'

module Gravatar

  def gravatar_for(email)
    hash = Digest::MD5.hexdigest(email.chomp.downcase)
    "http://www.gravatar.com/avatar/#{hash}"
  end

end

运行代码时收到的错误是

NoMethodError at/
undefined method `gravatar_for'...

宝石和回购可以在这里找到:https://rubygems.org/gems/snagagrav

3 个答案:

答案 0 :(得分:2)

最简单的方法不是制作自己的中间人扩展:

将其放入config.rb

require 'digest/md5'
helpers do
  def gravatar_for(email)
    hash = Digest::MD5.hexdigest(email.chomp.downcase)
    "http://www.gravatar.com/avatar/#{hash}"
  end
end

现在,您可以在模板中执行以下操作:

<%= gravatar_for(article.data.email) %>

答案 1 :(得分:0)

我假设您已成功尝试向config.rb添加类似内容:

require 'digest/md5'
class Gravatar < Middleman::Extension
  def initialize(app, options_hash={}, &block)
    super
    puts "#{options_hash.inspect}"
  end

  helpers do
    def make_a_link(url, text)
      "<a href='#{url}'>#{text}</a>"
    end

    def gravatar_for(email)
      hash = Digest::MD5.hexdigest(email.chomp.downcase)
      "http://www.gravatar.com/avatar/#{hash}"
    end
  end
end

::Middleman::Extensions.register(:gravatar, Gravatar)

set :css_dir, 'stylesheets'

set :js_dir, 'javascripts'

set :images_dir, 'images'

# Build-specific configuration
configure :build do
  activate :gravatar
end

然后在你的模板中:

---
title: Welcome to Middleman
email: example@mail.com
---

<div class="welcome">
  <h1>Middleman is Watching</h1>
  <p class="doc">
    <%= gravatar_for(current_page.data.email) %>
  </p><!-- .doc -->
</div><!-- .welcome -->

这对我有用。好像你需要将你的gem变成一个MiddleMan扩展并注册它。

答案 2 :(得分:0)

想出来!这是我做的:

在目录middleman-gravatar.rb

中创建了名为middleman-gravatar/lib/的gem
class MiddlemanGravatar < ::Middleman::Extension

  helpers do
    def gravatar_for(email, options_hash={})
      if email
        # Creates md5 hash for email address
        hash = Digest::MD5.hexdigest(email.chomp.downcase)
        # Returns Gravatar image for email (.jpg)
        "<img src='http://www.gravatar.com/avatar/#{hash}.jpg' />"
      else
        # Returns default mysterman image if no Gravatar exists
        "<img src='http://www.gravatar.com/avatar/?d=mm' />"
      end
    end
  end

end

::Middleman::Extensions.register(:middleman_gravatar, MiddlemanGravatar)

将此添加到config.rb文件

# Gravatar
require('middleman-gravatar/lib/middleman-gravatar')
activate :middleman_gravatar

将此添加到index.html.erb以显示Gravatar

<%= gravatar_for(article.data.gravatar) %>

并将其添加到文章文件的前端

---
gravatar: email@example.com
---