Skip to content

Instantly share code, notes, and snippets.

@lomefin
Last active August 29, 2015 14:16
Show Gist options
  • Save lomefin/a3bc286ecccfc874d28c to your computer and use it in GitHub Desktop.
Save lomefin/a3bc286ecccfc874d28c to your computer and use it in GitHub Desktop.
Compactando código para hacerlo más elegante, eficiente y legible.
#Tengo una wea que me llega una serie de causas de error y quiero convertir esas causales a íconos
#Entonces, puedo hacer esto
element = $('<span class="fa-stack fa-lg"><i class="fa fa-car fa-stack-1x"></i><i class="fa fa-ban fa-stack-2x text-danger"></i></span>') if cause == "transportation_exclusion"
element = $('<span class="fa-stack fa-lg"><i class="fa fa-car fa-stack-1x"></i><i class="fa fa-ban fa-stack-2x text-danger"></i></span>') if cause == "role_definition"
#Pero es una mierda y es muy larga la línea y no me gusta Entonces... switch!
switch cause
when "transportation_exclusion"
element = $('<span class="fa-stack fa-lg"><i class="fa fa-car fa-stack-1x"></i><i class="fa fa-ban fa-stack-2x text-danger"></i></span>')
when "profile_not_found"
element = $('<span class="fa-stack fa-lg"><i class="fa fa-car fa-stack-1x"></i><i class="fa fa-ban fa-stack-2x text-danger"></i></span>')
when "role_definition"
element = $('<span class="fa-stack fa-lg"><i class="fa fa-car fa-stack-1x"></i><i class="fa fa-ban fa-stack-2x text-danger"></i></span>')
when "location_not_confirmed"
element = $('<span class="fa-stack fa-lg"><i class="fa fa-car fa-stack-1x"></i><i class="fa fa-ban fa-stack-2x text-danger"></i></span>')
# Pero puta que repito weas, y estoy haciendo ifs... Entonces diccionario e interpolación de Strings
iconsForCauses =
"transportation_exclusion" : "car",
"profile_not_found": "user",
"role_definition": "clock-o",
"location_not_confirmed": "map-marker"
element = $("<span class='fa-stack fa-lg'><i class='fa fa-#{iconsForCauses[cause]} fa-stack-1x'></i><i class='fa fa-ban fa-stack-2x text-danger'></i></span>")
# Llega a verse excesivo si lo usarás una vez Pero en verdad esto está en un ciclo que recorre N filas y cada fila puede tener entre 0 y 4 causas de error. El diccionario vale la pena
# Aparte, es mucho más cómodo ir y cambiar la definición en el diccionario que en el código Esto incluso podría tirarlo a un archivo de configuracion (hay un i18n para javasript, aqui no lo usamos eso si)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment