diff --git a/README b/README index 4257ede..717ba64 100644 --- a/README +++ b/README @@ -59,6 +59,12 @@ Example | 2 | "Blog the plugin" | nil | +----+------------------------+---------------+ +# There's a convenient equivalent syntax for displaying an ordered list of columns, like :only and :methods: +>> puts Customer.find(31).purchases.to_table :id, :description, :met_due_date? +# which provides: +>> pt Customer.find(31).purchases, :id, :description, :met_due_date? +# resulting in the same output as above. + # If :inspect => false is used, the values will be shown in #to_s form rather than #inspect form: >> pt Customer.find(31).purchases, :only => [:id, :description, :due_on, :completed_at] diff --git a/lib/table_display.rb b/lib/table_display.rb index b358ef6..64fd3ba 100644 --- a/lib/table_display.rb +++ b/lib/table_display.rb @@ -1,10 +1,13 @@ module TableDisplay - def to_table(options = {}) - extra_methods = Array(options.delete(:methods) || []).collect(&:to_s) + def to_table(*args) + options = args.last.is_a?(Hash) ? args.pop : {} + extra_methods = args.length > 0 ? args.collect(&:to_s) : [] + extra_methods += Array(options.delete(:methods)).collect(&:to_s) if options[:methods] only_attributes = Array(options.delete(:only)).collect(&:to_s) if options[:only] + only_attributes ||= [] if args.length > 0 except_attributes = Array(options.delete(:except)).collect(&:to_s) if options[:except] - display_inspect = !options.has_key?(:inspect) || options.delete(:inspect) - raise "unknown options passed to to_table: #{options.keys.to_sentence}" unless options.empty? + display_inspect = options.nil? || !options.has_key?(:inspect) || options.delete(:inspect) + raise "unknown options passed to to_table: #{options.keys.to_sentence}" unless options.blank? column_lengths = ActiveSupport::OrderedHash.new diff --git a/test/table_display_test.rb b/test/table_display_test.rb index 8633d01..14fbdd2 100644 --- a/test/table_display_test.rb +++ b/test/table_display_test.rb @@ -124,6 +124,28 @@ def setup END end + test "#to_table accepts an unnamed list of arguments for column names" do + assert_equal < false).join("\n") ++----+------------+------------+ +| id | due_on | completed? | ++----+------------+------------+ +| 1 | 2009-03-25 | true | +| 2 | 2009-04-05 | false | ++----+------------+------------+ +END + end + test "#to_table also shows any :methods given as columns" do assert_equal < [:completed?, 'project_name']).join("\n") +----+------------+------------------------+------------------+--------------------------------+--------------------------------+--------------------------------+------------+------------------------+