Елена обнови решението на 26.11.2014 09:37 (преди почти 10 години)
+module UI
+ class TextScreen
+ def TextScreen.draw(&block)
+ screen = ResultScreenBuilder.new
+ screen.instance_eval(&block)
+ end
+ end
+
+ class ResultScreenBuilder
+ def initialize
+ @labels = ''
+ end
+
+ def label(text:, border: nil, style: nil)
+ label_result = LabelComponent.new
+ @labels << label_result.label(text: text, border: border, style: style)
+ end
+
+ def horizontal(border: nil, style: nil, &block)
+ result = HorizontalGroup.new(border: border, style: style)
+ result.instance_eval(&block)
+ result.build_result
+ end
+
+ def vertical(border: nil, style: nil, &block)
+ result = VerticalGroup.new(border: border, style: style)
+ result.instance_eval(&block)
+ result.build_result
+ end
+ end
+
+ class LabelComponent
+ def initialize
+ @result = ''
+ end
+
+ def label(text:, border: nil, style: nil)
+ if style
+ @result << "#{border}" + "#{text.send (style)}" + "#{border}"
+ else
+ @result << "#{border}" + text + "#{border}"
+ end
+ @result
+ end
+ end
+
+ class VerticalGroup
+ def initialize(border: nil, style: nil)
+ @labels = []
+ @result = ''
+ @style = style
+ @border = border
+ end
+
+ def label(text:, border: nil, style: nil)
+ label = LabelComponent.new
+ if style
+ @labels << label.label(text: text, border: border, style: style)
+ else
+ @labels << label.label(text: text, border: border, style: @style)
+ end
+ center_content
+ end
+
+ def vertical(border: nil, style: nil, &block)
+ result = VerticalGroup.new(border: border, style: style)
+ result.instance_eval(&block)
+ result.build_result
+ end
+
+ def horizontal(border: nil, style: nil, &block)
+ result = HorizontalGroup.new
+ result.instance_eval(&block)
+ @labels << "#{border}" + result.build_result + "#{border}"
+ end
+
+ def center_content
+ max_length = @labels.max_by { |label| label.length }.length
+ @labels.map! { |label| label.ljust(max_length) }
+ end
+
+ def build_result
+ @labels.each do |label|
+ @result << "#{@border}" << label << "#{@border}\n"
+ end
+ @result
+ end
+ end
+ class HorizontalGroup
+ def initialize(border: nil, style: nil)
+ @result = ''
+ @labels = []
+ @border = border
+ @style = style
+ end
+
+ def label(text:, border: nil, style: nil)
+ label = LabelComponent.new
+ if style
+ @labels << label.label(text: text, border: border, style: style)
+ else
+ @labels << label.label(text: text, border: border, style: @style)
+ end
+ end
+
+ def vertical(border: nil, style: nil, &block)
+ result = VerticalGroup.new(border: border, style: style)
+ result.instance_eval(&block)
+ @labels << result.build_result
+ end
+
+ def horizontal(border: nil, style: nil, &block)
+ @result_string << "#{border}"
+ inner_builder = HorizontalGroup.new
+ @result_string << inner_builder.instance_eval(&block)
+ @result_string << "#{border}"
+ end
+
+ def build_result
+ @labels.each do |label|
+ @result << label
+ end
+ "#{@border}" + @result + "#{@border}"
+ end
+ end
+end