Reputation: 4674
I am trying to call gravatar_for from one of my models. (Yes I realise this isn't strictly MVC, but I have a legitimate reason for doing it which I am not going into). I'm trying to include the helpers for Gravatar but I haven't been successful in finding what they are.
So far including it inside my class like so doesn't work:
class AnnotationPostedActivity < NewsfeedActivity
include GravatarHelper::PublicMethods
Upvotes: 1
Views: 858
Reputation: 7403
If this is a helper module you're trying to mix into your Model, then this is a signal that things need to be moved around a bit. Helpers are really view helpers, and should only be called from the view. If there's logic there that is also useful in the model itself, then move it to a lib. For example:
# lib/gravatar_utils.rb
module GravatarUtils
def gravatar_for(user)
# ...
end
end
# app/helpers/gravatar_helper.rb
class GravatarHelper
include GravatarUtils
def gravatar_image_tag(user)
url = gravatar_for(user)
# ...
end
end
# app/models/annotation_posted_activity.rb
class AnnotationPostedActivity < NewsfeedActivity
include GravatarUtils
end
Of course, it's probably easier to just use something like gravatar-ultimate
Upvotes: 1
Reputation: 2048
Assuming you are using the gravatar-plugin to generate image tags, there are a few problems to overcome. Note that the gravatar_for
method takes a user object as its first argument.
Mixing in GravatarHelper::PublicMethods
to your AnnotationPostedActivity
class gives all instances access to the method gravatar_for(user, options={})
. So you would say:
alice = User.new()
alice.respond_to?(:gravatar_for)
=> true
alice.gravatar_for
ArgumentError: wrong number of arguments (0 for 1)
# (you need to supply an argument - the method got zero but was expecting one)
alice.gravatar_for(alice)
=> "<img class=\"gravatar\" alt=\"\" width=\"50\" height=\"50\" src=\"http://www.gravatar.com/avatar/70375a32ad79987b9bc00cb20f7d1c95?rating=PG&size=50\" />
# (not what we want at all)
You see, you must supply the user
object as the first argument of the gravatar_for
method. So what you will have to do is
One that provides a module that looks at self.email
instead of requiring it as a method parameter.
It's easy. And there's already ruby code to follow. You will probably need to include some of Rails' helpers in your AnnotationPostedActivity
model
>> gravatar_url '[email protected]`
NoMethodError: undefined method `h' for main:Object ....
>> require 'active_support/core_ext/string/output_safety'
=> true
>> include ERB::Util
=> Object
>> gravatar_url '[email protected]`
=> "http://www.gravatar.com/avatar/fbaf55d6c2618cafe0a759cfe85967e0?rating=PG&size=50"
Upvotes: 4