Reputation: 35359
I'm new to Ruby (Ruby 1.9.3 / RoR 3.2). I wrote this function to create a gravatar.
def gravatar_for(user, options = { size: 50, default: 'identicon' } )
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
s = options[:size]
d = options[:default]
gravatar_url = "http://gravatar.com/avatar/#{gravatar_id}.png?s=#{s}&d=#{d}"
image_tag(gravatar_url, alt: user.name, class: 'gravatar')
end
Calling <%= gravatar_for user %>
works. Calling <%= gravatar_for user, size = 30 %> causes the default option identicon
to be lost. I assume this is because the hash in the method definition is getting overwritten by the hash I'm passing in from the caller.
How can I make it so that I can pass in some options while others default to what's specified in the method definition? I want to call <%= gravatar_for user, size: 30 %>
and have it return a gravatar with size 30 and in the style of identicon
, even though that argument was omitted from the caller.
Upvotes: 2
Views: 775
Reputation: 14851
You can set up a default options hash and then merge
the options that the user has passed in to that hash. This will only overwrite properties that the user has specified, and leave everything else alone:
def gravatar_for(user, options = {})
default = { size: 50, default: 'identicon' }
options = default.merge(options)
end
Upvotes: 6