Skip to content

Instantly share code, notes, and snippets.

@satoryu
Last active July 13, 2019 14:21
Show Gist options
  • Save satoryu/29f0fd3b7da52af19c57cd9ebb1ac243 to your computer and use it in GitHub Desktop.
Save satoryu/29f0fd3b7da52af19c57cd9ebb1ac243 to your computer and use it in GitHub Desktop.
Prototype of Table Syntax
class Table
attr_reader :header, :rows
def initialize(header, rows)
@header = header
@rows = rows
end
end
class Row
def initialize(elements)
@elements = Array(elements)
end
def |(elm)
@elements.push elm
self
end
def each
@elements.each do |elm|
yield elm
end
end
def slice(size)
@elements.each_slice(size).map { |elm| Row.new(elm) }
end
def to_s
@elements.to_s
end
end
module TableSyntax
[String, Integer].each do |klass|
refine klass do
def |(elm)
Row.new(self).|(elm)
end
end
end
def table(*header, &block)
row = block.call
[header, row.slice(header.size)]
end
end
class Table
include TableSyntax
using TableSyntax
def generate
@rows = table :name, :age do
'SU-METAL' | 22 |
'MOAMETAL' | 20
end
end
def to_s
@rows.map(&:to_s).join("\n")
end
end
puts Table.new.foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment