Ruby代码美化,在多行上分割长指令

时间:2011-09-09 09:58:59

标签: ruby code-formatting

我们如何编写以下语句以提高可读性?

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)

以下内容无法编译

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])

3 个答案:

答案 0 :(得分:54)

也可以做

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)

答案 1 :(得分:49)

这样做:

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)

答案 2 :(得分:14)

它应该在1.9中编译。在之前的版本中它确实无效。