Module: Cerata

Defined in:
lib/probatio/more.rb

Class Method Summary collapse

Class Method Details

.horizontal_a_to_s(a, indent = '') ⇒ Object

TODO deal with double width characters...



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/probatio/more.rb', line 69

def horizontal_a_to_s(a, indent='')

  return '[]' if a.empty?

  o = StringIO.new

  o << indent << '[ '
  a1 = a.dup; while e = a1.shift
    o << e.inspect
    o << ', ' if a1.any?
  end
  o << ' ]'

  o.string
end

.horizontal_h_to_s(h, indent = '') ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/probatio/more.rb', line 85

def horizontal_h_to_s(h, indent='')

  return '{}' if h.empty?

  o = StringIO.new

  o << indent << '{ '
  kvs = h.to_a; while kv = kvs.shift
    o << "#{kv.first}: " << kv[1].inspect
    o << ', ' if kvs.any?
  end
  o << ' }'

  o.string
end

.table_to_s(a, indent = '') ⇒ Object

A "table" here is an array of hashes



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/probatio/more.rb', line 116

def table_to_s(a, indent='')

  return '[]' if a.empty?

  all_keys =
    a.collect { |h| h.keys }.flatten.uniq.map(&:to_s)
  key_widths =
    all_keys.inject({}) { |h, k| h[k] = k.length; h }
  val_widths =
    a.inject({}) { |w, h|
      h.each { |k, v| k = k.to_s; w[k] = [ w[k] || 0, v.inspect.length ].max }
      w }

  o = StringIO.new

  o << indent << "[\n"

  a.each do |h|
    o << indent << '{ '
    kvs = h.to_a; while kv = kvs.shift
      k, v = kv[0].to_s, kv[1].inspect
      kl, vl = key_widths[k], val_widths[k]
      kf = "%#{kl}s"
      vf = (v.is_a?(String) && v.start_with?('"')) ? "%-#{vl}s" : "%#{vl}s"
      o << ("#{kf}: #{vf}" % [ k, v ])
      o << ', ' if kvs.any?
    end
    o << " },\n"
  end

  o << indent << ']'

  o.string
end

.vertical_h_to_s(h, indent = '') ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/probatio/more.rb', line 101

def vertical_h_to_s(h, indent='')

  return '{}' if h.empty?

  o = StringIO.new

  o << indent << "{\n"
  h.each { |k, v| o << indent << "#{k}: " << v.inspect << ",\n" }
  o << indent << '}'

  o.string
end