Pergunta

In my Rails app I have some default gravatar image, but I need it to be different in size in two pages. Say, in 1st page image height should be 50px, and on the 2nb page - 100px.

Question is: how I should set my code to both avoid duplication in methods and achive my goal? P.S. I believe I should add some changes to "image tag" in "gravatar_show" but all my attempts failed.

def gravatar_for(user)   # it's for 1'st page
  gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
  gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}"
  image_tag(gravatar_url, alt: user.name, class: "gravatar img-rounded")
end

def gravatar_show(user)  # it's for 2'nd page(show)
  gravatar_for user
  ........# missing code......
end

======================================

Sure, I can just duplicate and change class for each and use different classes in css but it looks ugly

def gravatar_for(user)
  gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
  gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}"
  image_tag(gravatar_url, alt: user.name, class: "gravatar img-rounded")
end

def gravatar_show(user)
  gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
  gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}"
  image_tag(gravatar_url, alt: user.name, class: "gravatar-show img-rounded")
end  
Foi útil?

Solução

Use lazy Stringevaluation "#{variable}":

def gravatar_for(user, show = nil)
  gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
  gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}"
  mod = "-show" if show
  image_tag(gravatar_url, alt: user.name, class: "gravatar#{mod} img-rounded")
end
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top