2

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.

Mohamad
  • 34,731
  • 32
  • 140
  • 219
  • Merging two hashes: http://stackoverflow.com/questions/1980794/how-can-i-merge-two-hashes-without-overwritten-duplicate-keys-in-ruby – joeytwiddle Jan 16 '15 at 23:09

1 Answers1

6

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
Mohamad
  • 34,731
  • 32
  • 140
  • 219
Ryan Brunner
  • 14,723
  • 1
  • 36
  • 52