The document discusses common mistakes made by workshop applicants including string concatenation versus string interpolation, control flow issues like nested if/else statements that could be simplified with guard clauses, N+1 query problems that can be solved with eager loading, passing too many options to methods, exposing secrets in code repositories, duplicating styles, and using incorrect syntax for the template language being used. It provides examples of better approaches for each case discussed.
6. I’d rather see you using Guard Clause
Again, this is a better choice in 99.99999% cases
return attempt_capture if kitten.cute?
kitten.groom
kitten.apply_ribbon
kitten.pat_on_the_head
9. N+1 Query
# models
class Cat < ActiveRecord::Base
belongs_to :crazy_cat_lady
end
class CrazyCatLady < ActiveRecord::Base
has_many :cats
end
# in controller
expose(:cats) { Cat.limit(5) }
# in view
cats.each do |cat|
= cat.crazy_cat_lady
end
10. This results in mayhem in your logs
Cat Load (0.9ms) SELECT 'cats'.* FROM 'cats'
CrazyCatLady Load (0.4ms) SELECT 'crazy_cat_ladies'.* FROM 'crazy_cat_ladies' WHERE
'crazy_cat_ladies'.'id' = ? ORDER BY 'crazy_cat_ladies'.'id' ASC LIMIT 1 [["id", 1]]
CrazyCatLady Load (0.3ms) SELECT 'crazy_cat_ladies'.* FROM 'crazy_cat_ladies' WHERE
'crazy_cat_ladies'.'id' = ? ORDER BY 'crazy_cat_ladies'.'id' ASC LIMIT 1 [["id", 2]]
CrazyCatLady Load (0.4ms) SELECT 'crazy_cat_ladies'.* FROM 'crazy_cat_ladies' WHERE
'crazy_cat_ladies'.'id' = ? ORDER BY 'crazy_cat_ladies'.'id' ASC LIMIT 1 [["id", 3]]
CrazyCatLady Load (0.3ms) SELECT 'crazy_cat_ladies'.* FROM 'crazy_cat_ladies' WHERE
'crazy_cat_ladies'.'id' = ? ORDER BY 'crazy_cat_ladies'.'id' ASC LIMIT 1 [["id", 4]]
CrazyCatLady Load (0.4ms) SELECT 'crazy_cat_ladies'.* FROM 'crazy_cat_ladies' WHERE
'crazy_cat_ladies'.'id' = ? ORDER BY 'crazy_cat_ladies'.'id' ASC LIMIT 1 [["id", 5]]
11. Eager loading for the rescue!
expose(:cats) { Cat.includes(:crazy_cat_ladies).limit(5)}
12. Cat Load (0.4ms) SELECT 'cats'•.* FROM 'cats'•
CrazyCatLady Load (0.4ms) SELECT 'crazy_cat_ladies'•.* FROM 'crazy_cat_ladies'•
WHERE 'crazy_cat_ladies'•.'•id'•IN (1,2,3,4,5)
Much better.
14. def cuddle_with_kitten(options = {})
# cuddling-related code
end
cuddle_with_kitten({cat: ‘Pinky’, cuddle: :furiously})
So many options!
15. You can drop the {braces} when options are
the last argument!
How cool is that? And cleaner too.
cuddle_with_kitten(cat: ‘Pinky’, cuddle: :furiously)
21. And last but not least...
# in view
= “#{t(‘something.clever’)}”
22. This is HAML, doug!
It tries very hard to be your best friend!
# in view
= t(‘something.clever’)}
~ or ~
#{t(‘something.even.cleverer’)} # Look, Ma! No ‘=’!