Q: How can I fix this problem without hacking the tutorial code too much? I would like to reduce moving away from the tutorial code.
I am working through the online Ruby on Rails Tutorial by Michael Hartl. In Chapter 7 we begin to bring in profile photos using the a Gravatar plugin. (This does not appear compatible with Rails 3 – but this is not the question.)
I have got the plugin working however my Rails App does not show the Gravatar image. It shows a text string. ie It injects the Gravatar code as text rather than an html tag.
Instead of showing the following in the file:
<img class="gravatar" alt="" width="52" height="52" src="http://www.gravatar.com/avatar/b58996c504c5638798eb6b511e6f49af?rating=PG&size=52" />
It shows this (displaying the text, rather than image):
<img class="gravatar" alt="" width="52" height="52" src="http://www.gravatar.com/avatar/b58996c504c5638798eb6b511e6f49af?rating=PG&amp;size=52" />
My view file contains:
<%= gravatar_for user, size: 52 %>
The Gravatar plugin contains (gravatar.rb):
def gravatar(email, options={})
src = h(gravatar_url(email, options))
options = DEFAULT_OPTIONS.merge(options)
[:class, :alt, :size].each { |opt| options[opt] = h(options[opt]) }
"<img class=\"#{options[:class]}\" alt=\"#{options[:alt]}\" width=\"#{options[:size]}\" height=\"#{options[:size]}\" src=\"#{src}\" />"
end
Other info:
I am working on a Windows 7 box running Rails 3.2.
Tell Rails that the HTML is trusted (and so shouldn’t be escaped) by using the
html_safemethod:Background: http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/
Incidentally you can, and probably should, sidestep this issue neatly and entirely by just using Rails’ built-in
image_taghelper, which has the bonus effect of getting rid of that long, ugly hard-coded string:(Don’t let that
"..." % optionsthrow you off—it’s basically shorthand forsprintf.)