Skip to content

Instantly share code, notes, and snippets.

@Fernan2
Last active December 22, 2015 19:39
Show Gist options
  • Save Fernan2/6520972 to your computer and use it in GitHub Desktop.
Save Fernan2/6520972 to your computer and use it in GitHub Desktop.
haml refactor
Initial ugly version:
- if @post
%div{ class: "blog-titulo#{ ' peque' if @blog.titulo.length > 60 }" }= @blog.titulo
- else
%h1{ class: "blog-titulo#{ ' peque' if @blog.titulo.length > 60 }" }= @blog.titulo
Nice, but doesn't work:
- h1_or_div = @post ? '%div' : '%h1'
= eval(h1_or_div){ class: "blog-titulo#{ ' peque' if @blog.titulo.length > 60 }" }= @blog.titulo
Works, but breaks DRY -> Seems WET (Will Enhance This)
- clase = { class: "blog-titulo#{ ' peque' if @blog.titulo.length > 60 }" }
- if @post
%div{ clase }= @blog.titulo
- else
%h1{ clase }= @blog.titulo
EDIT: Finally, it could be like this:
- clase_titulo = "blog-titulo#{' peque' if @blog.titulo.length > 60}"
= content_tag(@post ? :div : :h1, @blog.titulo, class: clase_titulo)
@jguitar
Copy link

jguitar commented Sep 11, 2013

  • div_or_h1 @post, class: "blog-titulo#{ ' peque' if @blog.titulo.length > 60 }" do
    = @blog.titulo

@Fernan2
Copy link
Author

Fernan2 commented Sep 11, 2013

It can work if I bypass HAML:

- h1_or_div = @post ? 'div' : 'h1'
<#{h1_or_div} class="blog-titulo#{ ' peque' if @blog.titulo.length > 60 }">#{@blog.titulo}</#{h1_or_div}>

@jonnyjava
Copy link

- clase = { class: "blog-titulo#{ ' peque' if @blog.titulo.length > 60 }" }
-@post ? '%div{ clase }' : '%h1{ clase }' 
= @blog.titulo

@Fernan2
Copy link
Author

Fernan2 commented Sep 11, 2013

This works and is (more or less) what I was looking for:

= content_tag(@post ? :div : :h1, @blog.titulo, class: "blog-titulo#{ ' peque' if @blog.titulo.length > 60 }")

@Fernan2
Copy link
Author

Fernan2 commented Sep 11, 2013

or in a cleaner way:

- clase_titulo = 'blog-titulo'
- clase_titulo += ' peque' if @blog.titulo.length > 60
= content_tag(@post ? :div : :h1, @blog.titulo, class: clase_titulo)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment