Class: View::Table

Inherits:
Formatter show all
Defined in:
lib/view/formatters/table.rb

Overview

Renders a table.

It uses a partial, which you can find in the gem under app/views/shared/_table.html.erb (and haml).

To change the table layout, you can copy the partial to your own application.

You can use a block to format attributes, or you can specify them with the fields option and trust them to be properly formatted automatically.

If you don't provide a block or fields, it will try to detect your fields automatically.

Use the partial option to render a different table partial.

When you use :as => :link, it will link to the record, or you specify the path option. Please see the documentation of View::Link for more information.

You will need to specify the class option to get a proper table headers when the collection is empty.

Examples:

Without a block:


= view @posts, :as => :table, :fields => [ :title, :author ]

With a block:


= view @posts, :as => :table do |tb|

  = tb.view :title, :path => :edit

  = tb.view :author do |formatter|
    = link_to formatter.to_s, user_path(formatter.value)

  = tb.view :published_at

With a different partial:


= view @posts, :as => :table, :partial => "shared/fancy_table"

Change the partial globally:


View::Table.partial = "shared/fancy_table"

Linking a column, without passing a block:


= view @posts, :as => :table,
  :link => :title, :link_options => { :path => :edit }

Defined Under Namespace

Classes: Cell, Column, Row

Instance Attribute Summary

Attributes inherited from Formatter

#block, #template, #value

Instance Method Summary collapse

Methods inherited from Formatter

#all_options, as, inherited, #options, skip_blank_formatter, #to_s, type

Instance Method Details

#columnsArray

The columns defined

Returns:



72
73
74
# File 'lib/view/formatters/table.rb', line 72

def columns
  @columns ||= []
end

#each {|Row| ... } ⇒ Object

Iterates over the collection and yields rows.

Yields:



78
79
80
81
82
# File 'lib/view/formatters/table.rb', line 78

def each
  value.each_with_index do |resource, index|
    yield Row.new(resource, self, index)
  end
end

#resource_classObject



84
85
86
# File 'lib/view/formatters/table.rb', line 84

def resource_class
  all_options[:class] || value.first.class
end

#view(attribute, options = {}) {|formatter| ... } ⇒ Object

This will add the th and td tags.

Parameters:

  • attribute (Symbol)

    The name of the attribute to be called on value

  • options (Hash) (defaults to: {})

    These will be delegated to the formatting of the attribute's value.

Yields:

  • (formatter)

    The block will be used for formatting the attribute's value



65
66
67
68
# File 'lib/view/formatters/table.rb', line 65

def view(attribute, options = {}, &block)
  columns << Column.new(attribute, options, block, self)
  nil
end