重构 这一段 slim 代码有办法优化吗?

leopku · 2016年10月21日 · 最后由 leopku 回复于 2016年10月24日 · 7265 次阅读
.tile.is-ancestor
  .tile.is-3.is-vertical
    .tile.is-parent.is-vertical
      - @projects.each_with_index do |project, index|
        - if index % 4 == 0
          .title.is-child.box
            p.title = index

  .tile.is-3.is-vertical
    .tile.is-parent.is-vertical
      - @projects.each_with_index do |project, index|
        - if index % 4 == 1
          .title.is-child.box
            p.title = index

  .tile.is-3.is-vertical
    .tile.is-parent.is-vertical
      - @projects.each_with_index do |project, index|
        - if index % 4 == 2
          .title.is-child.box
            p.title = index

  .tile.is-3.is-vertical
    .tile.is-parent.is-vertical
      - @projects.each_with_index do |project, index|
        - if index % 4 == 3
          .title.is-child.box
            p.title = index

贴代码同时要描述你想做什么。

没有明白你的业务逻辑,不过纯代码替换

.tile.is-ancestor
  - 4.times do |col|
    .tile.is-3.is-vertical
      .tile.is-parent.is-vertical
        - @projects.each_with_index do |project, index|
          - if index % 4 == col
            .title.is-child.box
              p.title = index

看看 each_slice 是否可以简化,亦或者 css 手段优化

.tile.is-ancestor
  - @projects.in_groups_of(4).transpose.each |projects_group|
    .tile.is-3.is-vertical
      .tile.is-parent.is-vertical
        - projects_group.compact.each do |project|
          .title.is-child.box
            p.title = index

ps: 好久不见咩 松哥

#3 楼 @zj0713001 好久不见,啥时候聚聚哈

#2 楼 @small_fish__

就是这个意思。谢谢鱼总。

不知道我理解的对不对

result = Array.new(4) { [] }
@projects.each_with_index do |v, i|
  result[i % 4] << [v, i]
end

.tile.is-ancestor
    .tile.is-3.is-vertical
      .tile.is-parent.is-vertical
        - result.each do |project|
            .title.is-child.box
              p.title = project[1]

相当于遍历两次@projects

#6 楼 @angelfan 借你的方案延展,用了 array.group_by

最后方案:

controller

group_number = 4
@result = @projects.to_a.group_by.with_index { |_, i| i%group_number }.values

view 中

result = Array.new(4) { [] }
@projects.each_with_index do |v, i|
  result[i % 4] << [v, i]
end

这一部分相当于移到 controller 中,view 的部分逻辑干净清晰了很多

缺点是 @groups = @projects.to_a.group_by.with_index { |_, i| i%group_number }.values 这一段的可读性下降了 😅

需要 登录 后方可回复, 如果你还没有账号请 注册新账号