Sha256: 041eef6e68646045b0669b71b9cda2fbad51d28fd1d2a6eee7b116e79f786b23

Contents?: true

Size: 1.48 KB

Versions: 8

Compression:

Stored size: 1.48 KB

Contents

module TableHelp
  class TableFor
    attr_reader :collection, :context, :options, :column_names, :strategies
    delegate :concat, :capture, :tag, to: :context

    def initialize(collection, context, options = {})
      @collection   = collection
      @context      = context
      @options      = default_options.merge(options)
      @column_names = []
      @strategies   = []
    end

    def column(name = nil, method_name = nil, &block)
      column_names << Formatter.format_attribute_name(name, collection)
      strategies << Strategy.new(name, block_given? ? block : method_name)
    end

    def to_html
      return if collection.empty?

      tag.table(options) do
        concat thead
        concat tbody
      end
    end

    private

      def thead
        tag.thead do
          tag.tr do
            column_names.each do |column_name|
              concat tag.th(column_name)
            end
          end
        end
      end

      def tbody
        tag.tbody do
          collection.each do |record|
            concat(
              tag.tr(class: "table-row-#{record.model_name.singular}#{record.to_param}") do
                strategies.each do |strategy|
                  concat tag.td(Formatter.format_value(strategy.name, strategy.to_value(record, context)), class: "col-#{strategy.name}")
                end
              end,
            )
          end
        end
      end

      def default_options
        TableHelp.config.default_options[:table_for] || {}
      end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
table_help-0.1.7 lib/table_help/table_for.rb
table_help-0.1.6 lib/table_help/table_for.rb
table_help-0.1.5 lib/table_help/table_for.rb
table_help-0.1.4 lib/table_help/table_for.rb
table_help-0.1.3 lib/table_help/table_for.rb
table_help-0.1.2 lib/table_help/table_for.rb
table_help-0.1.1 lib/table_help/table_for.rb
table_help-0.1.0 lib/table_help/table_for.rb