Украшение кода Ruby, разделение длинных инструкций на несколько строк - PullRequest
40 голосов
/ 09 сентября 2011

Как мы можем написать следующее утверждение для улучшения читабельности?

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 ]

54 голосов
/ 09 сентября 2011

Также возможно сделать

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)
49 голосов
/ 09 сентября 2011

Сделай так:

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)
14 голосов
/ 09 сентября 2011

Должен скомпилироваться в 1.9. В предыдущих версиях он действительно был недействительным.

...