Class: Megam::TextFormatter
- Inherits:
-
Object
- Object
- Megam::TextFormatter
- Defined in:
- lib/megam/core/text_formatter.rb
Instance Attribute Summary collapse
-
#data ⇒ Object
readonly
Returns the value of attribute data.
-
#ui ⇒ Object
readonly
Returns the value of attribute ui.
Instance Method Summary collapse
- #formatted_data ⇒ Object
-
#initialize(data, ui) ⇒ TextFormatter
constructor
A new instance of TextFormatter.
- #is_singleton(value) ⇒ Object
- #text_format(data) ⇒ Object
Constructor Details
#initialize(data, ui) ⇒ TextFormatter
Returns a new instance of TextFormatter.
6 7 8 9 10 11 12 13 14 15 16 17 |
# File 'lib/megam/core/text_formatter.rb', line 6 def initialize(data, ui) @ui = ui @data = if data.respond_to?(:display_hash) data.display_hash elsif data.kind_of?(Array) data elsif data.respond_to?(:to_hash) data.to_hash else data end end |
Instance Attribute Details
#data ⇒ Object (readonly)
Returns the value of attribute data.
4 5 6 |
# File 'lib/megam/core/text_formatter.rb', line 4 def data @data end |
#ui ⇒ Object (readonly)
Returns the value of attribute ui.
5 6 7 |
# File 'lib/megam/core/text_formatter.rb', line 5 def ui @ui end |
Instance Method Details
#formatted_data ⇒ Object
19 20 21 |
# File 'lib/megam/core/text_formatter.rb', line 19 def formatted_data @formatted_data ||= text_format(data) end |
#is_singleton(value) ⇒ Object
58 59 60 |
# File 'lib/megam/core/text_formatter.rb', line 58 def is_singleton(value) !(value.kind_of?(Array) || value.respond_to?(:keys)) end |
#text_format(data) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/megam/core/text_formatter.rb', line 23 def text_format(data) buffer = '' if data.respond_to?(:keys) justify_width = data.keys.map {|k| k.to_s.size }.max.to_i + 1 data.sort.each do |key, value| # key: ['value'] should be printed as key: value if value.kind_of?(Array) && value.size == 1 && is_singleton(value[0]) value = value[0] end if is_singleton(value) # Strings are printed as key: value. justified_key = ui.color("#{key}:".ljust(justify_width), :cyan) buffer << "#{justified_key} #{value}\n" else # Arrays and hashes get indented on their own lines. buffer << ui.color("#{key}:\n", :cyan) lines = text_format(value).split("\n") lines.each { |line| buffer << " #{line}\n" } end end elsif data.kind_of?(Array) data.each_index do |index| item = data[index] buffer << text_format(data[index]) # Separate items with newlines if it's an array of hashes or an # array of arrays buffer << "\n" if !is_singleton(data[index]) && index != data.size-1 end else buffer << "#{data}\n" end buffer end |