Liren Yeo
Liren Yeo

Reputation: 3451

Rails Active Admin - create helper function that wraps around column()

  index as: :reorderable_table do
    column :position
    column :full_name
    column 'Category', &:category_name
    column :avatar do |fm|
      attachment_img(fm.avatar)
    end
    column :banner do |fm|
      attachment_img(fm.banner)
    end
    column :description do |fm|
      fm.description.try(:truncate, 100)
    end
    column :short_profile do |fm|
      fm.short_profile.try(:truncate, 100)
    end
    actions
  end

Referring to the code above, even with some custom helper methods, I still find myself having to repeat the column do apply_logic end a lot.

How can I write helper methods that wrap around the 'column' function so that my output can become something like this:

  index as: :reorderable_table do
    column :position
    column :full_name
    rename_column :category_name, 'Category'
    img_column :avatar
    img_column :banner
    truncate_column :description
    truncate_column :short_profile
    actions
  end

Upvotes: 3

Views: 280

Answers (1)

Sjors Branderhorst
Sjors Branderhorst

Reputation: 2182

You can break up the IndexTableFor class in ActiveAdmin by placing the following inside an initializer. I placed it in config/initializers/active_admin_monkey_patches.rb

module ActiveAdmin
  module Views
    class IndexAsTable < ActiveAdmin::Component
      class IndexTableFor < ::ActiveAdmin::Views::TableFor
        def rename_column str, attr
          column(str) do |obj|
            obj.send(attr)
          end 
        end
        def img_column attr
          column(attr) do |obj|
            attachment_img(obj.send(attr))
          end
        end
        def truncate_column attr, length
          column(attr) do |obj|
            obj.send(attr).try(:truncate, length)
          end
        end
      end
    end
  end
end

Restart your rails server when making changes, as it is initializer code. Perhaps read the gem source, which in my case was located at

~/.rvm/gems/ruby-3.1.2@chirails/gems/activeadmin-2.13.1/lib/active_admin/views/index_as_table.rb

I found the location through running

bundle info activeadmin

Upvotes: 4

Related Questions