From 79e2d1d8b4673c7f174a36317ddeefb9e0d37a3f Mon Sep 17 00:00:00 2001 From: Florian Weingarten Date: Fri, 8 Jan 2016 18:38:10 +0000 Subject: [PATCH] Liquid::TablerowloopDrop --- lib/liquid.rb | 1 + lib/liquid/tablerowloop_drop.rb | 62 +++++++++++++++++++++++++++++++++ lib/liquid/tags/table_row.rb | 31 +++++------------ 3 files changed, 71 insertions(+), 23 deletions(-) create mode 100644 lib/liquid/tablerowloop_drop.rb diff --git a/lib/liquid.rb b/lib/liquid.rb index e8b3538..0872b30 100644 --- a/lib/liquid.rb +++ b/lib/liquid.rb @@ -48,6 +48,7 @@ require 'liquid/lexer' require 'liquid/parser' require 'liquid/i18n' require 'liquid/drop' +require 'liquid/tablerowloop_drop' require 'liquid/forloop_drop' require 'liquid/extensions' require 'liquid/errors' diff --git a/lib/liquid/tablerowloop_drop.rb b/lib/liquid/tablerowloop_drop.rb new file mode 100644 index 0000000..cda4a1e --- /dev/null +++ b/lib/liquid/tablerowloop_drop.rb @@ -0,0 +1,62 @@ +module Liquid + class TablerowloopDrop < Drop + def initialize(length, cols) + @length = length + @row = 1 + @col = 1 + @cols = cols + @index = 0 + end + + attr_reader :length, :col, :row + + def index + @index + 1 + end + + def index0 + @index + end + + def col0 + @col - 1 + end + + def rindex + @length - @index + end + + def rindex0 + @length - @index - 1 + end + + def first + @index == 0 + end + + def last + @index == @length - 1 + end + + def col_first + @col == 1 + end + + def col_last + @col == @cols + end + + protected + + def increment! + @index += 1 + + if @col == @cols + @col = 1 + @row += 1 + else + @col += 1 + end + end + end +end diff --git a/lib/liquid/tags/table_row.rb b/lib/liquid/tags/table_row.rb index efd4891..acd91e0 100644 --- a/lib/liquid/tags/table_row.rb +++ b/lib/liquid/tags/table_row.rb @@ -28,36 +28,21 @@ module Liquid cols = context.evaluate(@attributes['cols'.freeze]).to_i - row = 1 - col = 0 - result = "\n" context.stack do + tablerowloop = Liquid::TablerowloopDrop.new(length, cols) + context['tablerowloop'.freeze] = tablerowloop + collection.each_with_index do |item, index| context[@variable_name] = item - context['tablerowloop'.freeze] = { - 'length'.freeze => length, - 'index'.freeze => index + 1, - 'index0'.freeze => index, - 'col'.freeze => col + 1, - 'col0'.freeze => col, - 'rindex'.freeze => length - index, - 'rindex0'.freeze => length - index - 1, - 'first'.freeze => (index == 0), - 'last'.freeze => (index == length - 1), - 'col_first'.freeze => (col == 0), - 'col_last'.freeze => (col == cols - 1) - } - col += 1 + result << "" << super << '' - result << "" << super << '' - - if col == cols && (index != length - 1) - col = 0 - row += 1 - result << "\n" + if tablerowloop.col_last && !tablerowloop.last + result << "\n" end + + tablerowloop.send(:increment!) end end result << "\n"