Ruby code beautification, split long instructions on multiple lines
Asked Answered
S

3

47

How can we write the following statement to improve readability?

Promotion.joins(:category).where(["lft>=? and rgt<=?", c.lft, c.rgt]).joins(:shops).where(:promotions_per_shops => { :shop_id => shops_id }).count('id', :distinct => true)

The following doesn't compile

Promotion.joins(:category)
         .where(["lft>=? and rgt<=?", c.lft, c.rgt])
         .joins(:shops)
         .where(:promotions_per_shops => { :shop_id => shops_id })
         .count('id', :distinct => true)

syntax error, unexpected '.', expecting kEND
                     .where(["lft>=? and rgt<=?", c.lft, c.rgt])
Superbomb answered 9/9, 2011 at 9:58 Comment(0)
A
55

Do it like this:

Promotion.joins(:category).
         where(["lft>=? and rgt<=?", c.lft, c.rgt]).
         joins(:shops).
         where(:promotions_per_shops => { :shop_id => shops_id }).
         count('id', :distinct => true)
Application answered 9/9, 2011 at 10:3 Comment(0)
S
61

Also possible to do

Promotion.joins(:category) \
         .where(["lft>=? and rgt<=?", c.lft, c.rgt]) \
         .joins(:shops) \
         .where(:promotions_per_shops => { :shop_id => shops_id }) \
         .count('id', :distinct => true)
Superbomb answered 9/9, 2011 at 11:1 Comment(0)
A
55

Do it like this:

Promotion.joins(:category).
         where(["lft>=? and rgt<=?", c.lft, c.rgt]).
         joins(:shops).
         where(:promotions_per_shops => { :shop_id => shops_id }).
         count('id', :distinct => true)
Application answered 9/9, 2011 at 10:3 Comment(0)
C
14

It should compile in 1.9. In previous versions it was invalid indeed.

Caridadcarie answered 9/9, 2011 at 10:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.