hirber 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. checksums.yaml +7 -0
  2. data/.gemspec +21 -0
  3. data/.travis.yml +11 -0
  4. data/CHANGELOG.rdoc +165 -0
  5. data/CONTRIBUTING.md +1 -0
  6. data/LICENSE.txt +22 -0
  7. data/README.rdoc +205 -0
  8. data/Rakefile +35 -0
  9. data/lib/bond/completions/hirb.rb +15 -0
  10. data/lib/hirb.rb +84 -0
  11. data/lib/hirb/console.rb +43 -0
  12. data/lib/hirb/dynamic_view.rb +113 -0
  13. data/lib/hirb/formatter.rb +126 -0
  14. data/lib/hirb/helpers.rb +18 -0
  15. data/lib/hirb/helpers/auto_table.rb +24 -0
  16. data/lib/hirb/helpers/markdown_table.rb +14 -0
  17. data/lib/hirb/helpers/object_table.rb +14 -0
  18. data/lib/hirb/helpers/parent_child_tree.rb +24 -0
  19. data/lib/hirb/helpers/tab_table.rb +24 -0
  20. data/lib/hirb/helpers/table.rb +376 -0
  21. data/lib/hirb/helpers/table/filters.rb +10 -0
  22. data/lib/hirb/helpers/table/resizer.rb +82 -0
  23. data/lib/hirb/helpers/tree.rb +181 -0
  24. data/lib/hirb/helpers/unicode_table.rb +15 -0
  25. data/lib/hirb/helpers/vertical_table.rb +37 -0
  26. data/lib/hirb/import_object.rb +10 -0
  27. data/lib/hirb/menu.rb +226 -0
  28. data/lib/hirb/pager.rb +106 -0
  29. data/lib/hirb/string.rb +44 -0
  30. data/lib/hirb/util.rb +96 -0
  31. data/lib/hirb/version.rb +3 -0
  32. data/lib/hirb/view.rb +272 -0
  33. data/lib/hirb/views.rb +8 -0
  34. data/lib/hirb/views/couch_db.rb +11 -0
  35. data/lib/hirb/views/misc_db.rb +15 -0
  36. data/lib/hirb/views/mongo_db.rb +17 -0
  37. data/lib/hirb/views/orm.rb +11 -0
  38. data/lib/hirb/views/rails.rb +19 -0
  39. data/lib/ripl/hirb.rb +15 -0
  40. data/test/auto_table_test.rb +33 -0
  41. data/test/console_test.rb +27 -0
  42. data/test/dynamic_view_test.rb +94 -0
  43. data/test/formatter_test.rb +176 -0
  44. data/test/hirb_test.rb +39 -0
  45. data/test/import_test.rb +9 -0
  46. data/test/menu_test.rb +272 -0
  47. data/test/object_table_test.rb +79 -0
  48. data/test/pager_test.rb +162 -0
  49. data/test/resizer_test.rb +62 -0
  50. data/test/table_test.rb +667 -0
  51. data/test/test_helper.rb +60 -0
  52. data/test/tree_test.rb +184 -0
  53. data/test/util_test.rb +59 -0
  54. data/test/view_test.rb +178 -0
  55. data/test/views_test.rb +22 -0
  56. metadata +164 -0
@@ -0,0 +1,24 @@
1
+ class Hirb::Helpers::ParentChildTree < Hirb::Helpers::Tree
2
+ class <<self
3
+ # Starting with the given node, this builds a tree by recursively calling a children method.
4
+ # Takes same options as Hirb::Helper::Table.render with some additional ones below.
5
+ # ==== Options:
6
+ # [:value_method] Method or proc to call to display as a node's value. If not given, uses :name if node
7
+ # responds to :name or defaults to :object_id.
8
+ # [:children_method] Method or proc to call to obtain a node's children. Default is :children.
9
+ def render(root_node, options={})
10
+ value_method = options[:value_method] || (root_node.respond_to?(:name) ? :name : :object_id)
11
+ @value_method = value_method.is_a?(Proc) ? value_method : lambda {|n| n.send(value_method) }
12
+ children_method = options[:children_method] || :children
13
+ @children_method = children_method.is_a?(Proc) ? children_method : lambda {|n| n.send(children_method)}
14
+ @nodes = []
15
+ build_node(root_node, 0)
16
+ super(@nodes, options)
17
+ end
18
+
19
+ def build_node(node, level) #:nodoc:
20
+ @nodes << {:value=>@value_method.call(node), :level=>level}
21
+ @children_method.call(node).each {|e| build_node(e, level + 1)}
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,24 @@
1
+ class Hirb::Helpers::TabTable < Hirb::Helpers::Table
2
+ DELIM = "\t"
3
+
4
+ # Renders a tab-delimited table
5
+ def self.render(rows, options={})
6
+ new(rows, {:description => false}.merge(options)).render
7
+ end
8
+
9
+ def render_header
10
+ @headers ? render_table_header : []
11
+ end
12
+
13
+ def render_table_header
14
+ [ format_values(@headers).join(DELIM) ]
15
+ end
16
+
17
+ def render_rows
18
+ @rows.map { |row| format_values(row).join(DELIM) }
19
+ end
20
+
21
+ def render_footer
22
+ []
23
+ end
24
+ end
@@ -0,0 +1,376 @@
1
+ # -*- encoding : utf-8 -*-
2
+ require 'hirb/helpers/table/filters'
3
+ require 'hirb/helpers/table/resizer'
4
+
5
+ module Hirb
6
+ # Base Table class from which other table classes inherit.
7
+ # By default, a table is constrained to a default width but this can be adjusted
8
+ # via the max_width option or Hirb::View.width.
9
+ # Rows can be an array of arrays or an array of hashes.
10
+ #
11
+ # An array of arrays ie [[1,2], [2,3]], would render:
12
+ # +---+---+
13
+ # | 0 | 1 |
14
+ # +---+---+
15
+ # | 1 | 2 |
16
+ # | 2 | 3 |
17
+ # +---+---+
18
+ #
19
+ # By default, the fields/columns are the numerical indices of the array.
20
+ #
21
+ # An array of hashes ie [{:age=>10, :weight=>100}, {:age=>80, :weight=>500}], would render:
22
+ # +-----+--------+
23
+ # | age | weight |
24
+ # +-----+--------+
25
+ # | 10 | 100 |
26
+ # | 80 | 500 |
27
+ # +-----+--------+
28
+ #
29
+ # By default, the fields/columns are the keys of the first hash.
30
+ #
31
+ # === Custom Callbacks
32
+ # Callback methods can be defined to add your own options that modify rows right before they are rendered.
33
+ # Here's an example that allows for searching with a :query option:
34
+ # module Query
35
+ # # Searches fields given a query hash
36
+ # def query_callback(rows, options)
37
+ # return rows unless options[:query]
38
+ # options[:query].map {|field,query|
39
+ # rows.select {|e| e[field].to_s =~ /#{query}/i }
40
+ # }.flatten.uniq
41
+ # end
42
+ # end
43
+ # Hirb::Helpers::Table.send :include, Query
44
+ #
45
+ # >> puts Hirb::Helpers::Table.render [{:name=>'batman'}, {:name=>'robin'}], :query=>{:name=>'rob'}
46
+ # +-------+
47
+ # | name |
48
+ # +-------+
49
+ # | robin |
50
+ # +-------+
51
+ # 1 row in set
52
+ #
53
+ # Callback methods:
54
+ # * must be defined in Helpers::Table and end in '_callback'.
55
+ # * should expect rows and a hash of render options. Rows will be an array of hashes.
56
+ # * are expected to return an array of hashes.
57
+ # * are invoked in alphabetical order.
58
+ # For a thorough example, see {Boson::Pipe}[http://github.com/cldwalker/boson/blob/master/lib/boson/pipe.rb].
59
+ #--
60
+ # derived from http://gist.github.com/72234
61
+ class Helpers::Table
62
+ BORDER_LENGTH = 3 # " | " and "-+-" are the borders
63
+ MIN_FIELD_LENGTH = 3
64
+ class TooManyFieldsForWidthError < StandardError; end
65
+
66
+ CHARS = {
67
+ :top => {:left => '+', :center => '+', :right => '+', :horizontal => '-',
68
+ :vertical => {:outside => '|', :inside => '|'} },
69
+ :middle => {:left => '+', :center => '+', :right => '+', :horizontal => '-'},
70
+ :bottom => {:left => '+', :center => '+', :right => '+', :horizontal => '-',
71
+ :vertical => {:outside => '|', :inside => '|'} }
72
+ }
73
+
74
+ class << self
75
+
76
+ # Main method which returns a formatted table.
77
+ # ==== Options:
78
+ # [*:fields*] An array which overrides the default fields and can be used to indicate field order.
79
+ # [*:headers*] A hash of fields and their header names. Fields that aren't specified here default to their name.
80
+ # When set to false, headers are hidden. Can also be an array but only for array rows.
81
+ # [*:max_fields*] A hash of fields and their maximum allowed lengths. Maximum length can also be a percentage of the total width
82
+ # (decimal less than one). When a field exceeds it's maximum then it's
83
+ # truncated and has a ... appended to it. Fields that aren't specified have no maximum.
84
+ # [*:max_width*] The maximum allowed width of all fields put together including field borders. Only valid when :resize is true.
85
+ # Default is Hirb::View.width.
86
+ # [*:resize*] Resizes table to display all columns in allowed :max_width. Default is true. Setting this false will display the full
87
+ # length of each field.
88
+ # [*:number*] When set to true, numbers rows by adding a :hirb_number column as the first column. Default is false.
89
+ # [*:change_fields*] A hash to change old field names to new field names. This can also be an array of new names but only for array rows.
90
+ # This is useful when wanting to change auto-generated keys to more user-friendly names i.e. for array rows.
91
+ # [*:grep_fields*] A regexp that selects which fields to display. By default this is not set and applied.
92
+ # [*:filters*] A hash of fields and their filters, applied to every row in a field. A filter can be a proc, an instance method
93
+ # applied to the field value or a Filters method. Also see the filter_classes attribute below.
94
+ # [*:header_filter*] A filter, like one in :filters, that is applied to all headers after the :headers option.
95
+ # [*:filter_any*] When set to true, any cell defaults to being filtered by its class in :filter_classes.
96
+ # Default Hirb::Helpers::Table.filter_any().
97
+ # [*:filter_classes*] Hash which maps classes to filters. Default is Hirb::Helpers::Table.filter_classes().
98
+ # [*:all_fields*] When set to true, renders fields in all rows. Valid only in rows that are hashes. Default is false.
99
+ # [*:description*] When set to true, renders row count description at bottom. Default is true.
100
+ # [*:escape_special_chars*] When set to true, escapes special characters \n,\t,\r so they don't disrupt tables. Default is false for
101
+ # vertical tables and true for anything else.
102
+ # [*:vertical*] When set to true, renders a vertical table using Hirb::Helpers::VerticalTable. Default is false.
103
+ # [*:unicode*] When set to true, renders a unicode table using Hirb::Helpers::UnicodeTable. Default is false.
104
+ # [*:tab*] When set to true, renders a tab-delimited table using Hirb::Helpers::TabTable. Default is false.
105
+ # [*:style*] Choose style of table: :simple, :vertical, :unicode, :tab or :markdown. :simple
106
+ # just uses the default render. Other values map to a capitalized namespace in format
107
+ # Hirb::Helpers::OptionValTable.
108
+ #
109
+ # Examples:
110
+ # Hirb::Helpers::Table.render [[1,2], [2,3]]
111
+ # Hirb::Helpers::Table.render [[1,2], [2,3]], :max_fields=>{0=>10}, :header_filter=>:capitalize
112
+ # Hirb::Helpers::Table.render [['a',1], ['b',2]], :change_fields=>%w{letters numbers}, :max_fields=>{'numbers'=>0.4}
113
+ # Hirb::Helpers::Table.render [{:age=>10, :weight=>100}, {:age=>80, :weight=>500}]
114
+ # Hirb::Helpers::Table.render [{:age=>10, :weight=>100}, {:age=>80, :weight=>500}], :headers=>{:weight=>"Weight(lbs)"}
115
+ # Hirb::Helpers::Table.render [{:age=>10, :weight=>100}, {:age=>80, :weight=>500}], :filters=>{:age=>[:to_f]}
116
+ # Hirb::Helpers::Table.render [{:age=>10, :weight=>100}, {:age=>80, :weight=>500}], :style=> :simple}
117
+ def render(rows, options={})
118
+ choose_style(rows, options)
119
+ rescue TooManyFieldsForWidthError
120
+ $stderr.puts "", "** Hirb Warning: Too many fields for the current width. Configure your width " +
121
+ "and/or fields to avoid this error. Defaulting to a vertical table. **"
122
+ Helpers::VerticalTable.render(rows, options)
123
+ end
124
+
125
+ def choose_style(rows, options)
126
+ case options[:style]
127
+ when :vertical
128
+ Helpers::VerticalTable.render(rows, options)
129
+ when :unicode
130
+ Helpers::UnicodeTable.render(rows, options)
131
+ when :tab
132
+ Helpers::TabTable.render(rows, options)
133
+ when :markdown
134
+ Helpers::MarkdownTable.render(rows, options)
135
+ when :simple
136
+ new(rows, options).render
137
+ else
138
+ options[:vertical] ? Helpers::VerticalTable.render(rows, options) :
139
+ options[:unicode] ? Helpers::UnicodeTable.render(rows, options) :
140
+ options[:tab] ? Helpers::TabTable.render(rows, options) :
141
+ options[:markdown] ? Helpers::MarkdownTable.render(rows, options) :
142
+ new(rows, options).render
143
+ end
144
+ end
145
+ private :choose_style
146
+
147
+ # A hash which maps a cell value's class to a filter. This serves to set a default filter per field if all of its
148
+ # values are a class in this hash. By default, Array values are comma joined and Hashes are inspected.
149
+ # See the :filter_any option to apply this filter per value.
150
+ attr_accessor :filter_classes
151
+ # Boolean which sets the default for :filter_any option.
152
+ attr_accessor :filter_any
153
+ # Holds last table object created
154
+ attr_accessor :last_table
155
+ end
156
+ self.filter_classes = { Array=>:comma_join, Hash=>:inspect }
157
+
158
+
159
+ def chars
160
+ self.class.const_get(:CHARS)
161
+ end
162
+
163
+ #:stopdoc:
164
+ attr_accessor :width, :max_fields, :field_lengths, :fields
165
+ def initialize(rows, options={})
166
+ raise ArgumentError, "Table must be an array of hashes or array of arrays" unless rows.is_a?(Array) &&
167
+ (rows[0].is_a?(Hash) or rows[0].is_a?(Array) or rows.empty?)
168
+ @options = {:description=>true, :filters=>{}, :change_fields=>{}, :escape_special_chars=>true,
169
+ :filter_any=>Helpers::Table.filter_any, :resize=>true}.merge(options)
170
+ @fields = set_fields(rows)
171
+ @fields = @fields.select {|e| e.to_s[@options[:grep_fields]] } if @options[:grep_fields]
172
+ @rows = set_rows(rows)
173
+ @headers = set_headers
174
+ if @options[:number]
175
+ @headers[:hirb_number] ||= "number"
176
+ @fields.unshift :hirb_number
177
+ end
178
+ Helpers::Table.last_table = self
179
+ end
180
+
181
+ def set_fields(rows)
182
+ @options[:change_fields] = array_to_indices_hash(@options[:change_fields]) if @options[:change_fields].is_a?(Array)
183
+ return @options[:fields].dup if @options[:fields]
184
+
185
+ fields = if rows[0].is_a?(Hash)
186
+ keys = @options[:all_fields] ? rows.map {|e| e.keys}.flatten.uniq : rows[0].keys
187
+ keys.sort {|a,b| a.to_s <=> b.to_s}
188
+ else
189
+ rows[0].is_a?(Array) ? (0..rows[0].length - 1).to_a : []
190
+ end
191
+
192
+ @options[:change_fields].each do |oldf, newf|
193
+ (index = fields.index(oldf)) && fields[index] = newf
194
+ end
195
+ fields
196
+ end
197
+
198
+ def set_rows(rows)
199
+ rows = Array(rows)
200
+ if rows[0].is_a?(Array)
201
+ rows = rows.inject([]) {|new_rows, row|
202
+ new_rows << array_to_indices_hash(row)
203
+ }
204
+ end
205
+ @options[:change_fields].each do |oldf, newf|
206
+ rows.each {|e| e[newf] = e.delete(oldf) if e.key?(oldf) }
207
+ end
208
+ rows = filter_values(rows)
209
+ rows.each_with_index {|e,i| e[:hirb_number] = (i + 1).to_s} if @options[:number]
210
+ deleted_callbacks = Array(@options[:delete_callbacks]).map {|e| "#{e}_callback" }
211
+ (methods.grep(/_callback$/).map {|e| e.to_s} - deleted_callbacks).sort.each do |meth|
212
+ rows = send(meth, rows, @options.dup)
213
+ end
214
+ validate_values(rows)
215
+ rows
216
+ end
217
+
218
+ def set_headers
219
+ headers = @fields.inject({}) {|h,e| h[e] = e.to_s; h}
220
+ if @options.has_key?(:headers)
221
+ headers = @options[:headers].is_a?(Hash) ? headers.merge(@options[:headers]) :
222
+ (@options[:headers].is_a?(Array) ? array_to_indices_hash(@options[:headers]) : @options[:headers])
223
+ end
224
+ if @options[:header_filter]
225
+ headers.each {|k,v|
226
+ headers[k] = call_filter(@options[:header_filter], v)
227
+ }
228
+ end
229
+ headers
230
+ end
231
+
232
+ def render
233
+ body = []
234
+ unless @rows.length == 0
235
+ setup_field_lengths
236
+ body += render_header
237
+ body += render_rows
238
+ body += render_footer
239
+ end
240
+ body << render_table_description if @options[:description]
241
+ body.join("\n")
242
+ end
243
+
244
+ def render_header
245
+ @headers ? render_table_header : [render_border(:top)]
246
+ end
247
+
248
+ def render_footer
249
+ [render_border(:bottom)]
250
+ end
251
+
252
+ def render_table_header
253
+ title_row = chars[:top][:vertical][:outside] + ' ' +
254
+ format_values(@headers).join(' ' + chars[:top][:vertical][:inside] +' ') +
255
+ ' ' + chars[:top][:vertical][:outside]
256
+ [render_border(:top), title_row, render_border(:middle)]
257
+ end
258
+
259
+ def render_border(which)
260
+ chars[which][:left] + chars[which][:horizontal] +
261
+ @fields.map {|f| chars[which][:horizontal] * @field_lengths[f] }.
262
+ join(chars[which][:horizontal] + chars[which][:center] + chars[which][:horizontal]) +
263
+ chars[which][:horizontal] + chars[which][:right]
264
+ end
265
+
266
+ def format_values(values)
267
+ @fields.map {|field| format_cell(values[field], @field_lengths[field]) }
268
+ end
269
+
270
+ def format_cell(value, cell_width)
271
+ text = String.size(value) > cell_width ?
272
+ (
273
+ (cell_width < 5) ? String.slice(value, 0, cell_width) : String.slice(value, 0, cell_width - 3) + '...'
274
+ ) : value
275
+ String.ljust(text, cell_width)
276
+ end
277
+
278
+ def render_rows
279
+ @rows.map do |row|
280
+ chars[:bottom][:vertical][:outside] + ' ' +
281
+ format_values(row).join(' ' + chars[:bottom][:vertical][:inside] + ' ') +
282
+ ' ' + chars[:bottom][:vertical][:outside]
283
+ end
284
+ end
285
+
286
+ def render_table_description
287
+ (@rows.length == 0) ? "0 rows in set" :
288
+ "#{@rows.length} #{@rows.length == 1 ? 'row' : 'rows'} in set"
289
+ end
290
+
291
+ def setup_field_lengths
292
+ @field_lengths = default_field_lengths
293
+ if @options[:resize]
294
+ raise TooManyFieldsForWidthError if @fields.size > self.actual_width.to_f / MIN_FIELD_LENGTH
295
+ Resizer.resize!(self)
296
+ else
297
+ enforce_field_constraints
298
+ end
299
+ end
300
+
301
+ def enforce_field_constraints
302
+ max_fields.each {|k,max| @field_lengths[k] = max if @field_lengths[k].to_i > max }
303
+ end
304
+
305
+ undef :max_fields
306
+ def max_fields
307
+ @max_fields ||= (@options[:max_fields] ||= {}).each {|k,v|
308
+ @options[:max_fields][k] = (actual_width * v.to_f.abs).floor if v.to_f.abs < 1
309
+ }
310
+ end
311
+
312
+ def actual_width
313
+ @actual_width ||= self.width - (@fields.size * BORDER_LENGTH + 1)
314
+ end
315
+
316
+ undef :width
317
+ def width
318
+ @width ||= @options[:max_width] || View.width
319
+ end
320
+
321
+ # find max length for each field; start with the headers
322
+ def default_field_lengths
323
+ field_lengths = @headers ? @headers.inject({}) {|h,(k,v)| h[k] = String.size(v); h} :
324
+ @fields.inject({}) {|h,e| h[e] = 1; h }
325
+ @rows.each do |row|
326
+ @fields.each do |field|
327
+ len = String.size(row[field])
328
+ field_lengths[field] = len if len > field_lengths[field].to_i
329
+ end
330
+ end
331
+ field_lengths
332
+ end
333
+
334
+ def set_filter_defaults(rows)
335
+ @filter_classes.each do |klass, filter|
336
+ @fields.each {|field|
337
+ if rows.all? {|r| r[field].class == klass }
338
+ @options[:filters][field] ||= filter
339
+ end
340
+ }
341
+ end
342
+ end
343
+
344
+ def filter_values(rows)
345
+ @filter_classes = Helpers::Table.filter_classes.merge @options[:filter_classes] || {}
346
+ set_filter_defaults(rows) unless @options[:filter_any]
347
+ rows.map {|row|
348
+ @fields.inject({}) {|new_row,f|
349
+ (filter = @options[:filters][f]) || (@options[:filter_any] && (filter = @filter_classes[row[f].class]))
350
+ new_row[f] = filter ? call_filter(filter, row[f]) : row[f]
351
+ new_row
352
+ }
353
+ }
354
+ end
355
+
356
+ def call_filter(filter, val)
357
+ filter.is_a?(Proc) ? filter.call(val) :
358
+ val.respond_to?(Array(filter)[0]) ? val.send(*filter) : Filters.send(filter, val)
359
+ end
360
+
361
+ def validate_values(rows)
362
+ rows.each {|row|
363
+ @fields.each {|f|
364
+ row[f] = row[f].to_s || ''
365
+ row[f] = row[f].gsub(/(\t|\r|\n)/) {|e| e.dump.gsub('"','') } if @options[:escape_special_chars]
366
+ }
367
+ }
368
+ end
369
+
370
+ # Converts an array to a hash mapping a numerical index to its array value.
371
+ def array_to_indices_hash(array)
372
+ array.inject({}) {|hash,e| hash[hash.size] = e; hash }
373
+ end
374
+ #:startdoc:
375
+ end
376
+ end
@@ -0,0 +1,10 @@
1
+ class Hirb::Helpers::Table
2
+ # Contains filter methods used by :filters option. To define a custom filter, simply open this module and create a method
3
+ # that take one argument, the value you will be filtering.
4
+ module Filters
5
+ extend self
6
+ def comma_join(arr) #:nodoc:
7
+ arr.join(', ')
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,82 @@
1
+ class Hirb::Helpers::Table
2
+ # Resizes a table's fields to the table's max width.
3
+ class Resizer
4
+ # Modifies field_lengths to fit within width. Also enforces a table's max_fields.
5
+ def self.resize!(table)
6
+ obj = new(table)
7
+ obj.resize
8
+ obj.field_lengths
9
+ end
10
+
11
+ #:stopdoc:
12
+ attr_reader :field_lengths
13
+ def initialize(table)
14
+ @table, @width, @field_size = table, table.actual_width, table.fields.size
15
+ @field_lengths = table.field_lengths
16
+ @original_field_lengths = @field_lengths.dup
17
+ end
18
+
19
+ def resize
20
+ adjust_long_fields || default_restrict_field_lengths
21
+ @table.enforce_field_constraints
22
+ add_extra_width
23
+ end
24
+
25
+ # Simple algorithm which allows smaller fields to be displayed while
26
+ # restricting longer fields to an average_long_field
27
+ def adjust_long_fields
28
+ while (total_length = sum(@field_lengths.values)) > @width
29
+ average_field = total_length / @field_size.to_f
30
+ long_lengths = @field_lengths.values.select {|e| e > average_field }
31
+ return false if long_lengths.empty?
32
+
33
+ # adjusts average long field by ratio with @width
34
+ average_long_field = sum(long_lengths)/long_lengths.size * @width/total_length
35
+ @field_lengths.each {|f,length|
36
+ @field_lengths[f] = average_long_field if length > average_long_field
37
+ }
38
+ end
39
+ true
40
+ end
41
+
42
+ # Produces a field_lengths which meets the @width requirement
43
+ def default_restrict_field_lengths
44
+ original_total_length = sum @original_field_lengths.values
45
+ # set fields by their relative weight to original length
46
+ new_lengths = @original_field_lengths.inject({}) {|t,(k,v)|
47
+ t[k] = (v / original_total_length.to_f * @width).to_i; t }
48
+
49
+ # set all fields the same if relative doesn't work
50
+ unless new_lengths.values.all? {|e| e > MIN_FIELD_LENGTH} && (sum(new_lengths.values) <= @width)
51
+ new_lengths = @field_lengths.inject({}) {|t,(k,_v)| t[k] = @width / @field_size; t }
52
+ end
53
+ @field_lengths.each {|k,v| @field_lengths[k] = new_lengths[k] }
54
+ end
55
+
56
+ def add_extra_width
57
+ added_width = 0
58
+ extra_width = @width - sum(@field_lengths.values)
59
+ unmaxed_fields = @field_lengths.keys.select {|f| !remaining_width(f).zero? }
60
+ # order can affect which one gets the remainder so let's keep it consistent
61
+ unmaxed_fields = unmaxed_fields.sort_by {|e| e.to_s}
62
+
63
+ unmaxed_fields.each_with_index do |f, i|
64
+ extra_per_field = (extra_width - added_width) / (unmaxed_fields.size - i)
65
+ add_to_field = remaining_width(f) < extra_per_field ? remaining_width(f) : extra_per_field
66
+ added_width += add_to_field
67
+ @field_lengths[f] += add_to_field
68
+ end
69
+ end
70
+
71
+ def remaining_width(field)
72
+ (@remaining_width ||= {})[field] ||= begin
73
+ (@table.max_fields[field] || @original_field_lengths[field]) - @field_lengths[field]
74
+ end
75
+ end
76
+
77
+ def sum(arr)
78
+ arr.inject {|t,e| t += e } || 0
79
+ end
80
+ #:startdoc:
81
+ end
82
+ end