How to make Active Admin column Html_safe and replace boolean values with some icons in better way

I was working on ActiveAdmin views and as we are using html editor for some of our text fields so we wanted to make sure when we are showing that html content in the application. It should be readable and without html tags.

To do that generally it is mentioned to use a block for the field and use .html_safe method. However I did not like this approach, as we have too many fields where I have to call html_safe method and I was not keen to write block for each fields. I know 🙂 I am lazy in that way. However, if I use that approach that means it is not DRY.
Here is the example to explain, what I mean by writing block for each column.


ActiveAdmin.register Post do
index do
selectable_column
column :comment do | post |
post.comment.html_safe
end
column :description do | post |
post.description.html_safe
end
column: isPrivate
column :website_url
actions
end
end

So I and my colleague Devilal was looking for a better approach and thanks to him he found out and suggested approach write a custom method for the column of the ActiveAdmin view. Now I have wrote a html_column method and that will actually return html_safe data and I will call this method in my ActiveAdmin view.
Basically we are extending Active Admin class ActiveAdmin::Views::TableFor and ActiveAdmin::Views::AttributesTable and we have added new methods html_column, html_row, bool_col and bool_row to display data in html safe format and boolean value with a nice tick and cross icon

We will add this code to a new file and you can put that file under
app/admin/lib folder or else add code to config/initializer/actice_admin.rb


module ActiveAdmin
module Views
class TableFor
def html_column(attribute)
column(attribute){ |model| model[attribute].html_safe }
end
def bool_column(attribute)
column(attribute){ |model| model[attribute] ? '✔'.html_safe : '✗'.html_safe }
end
end
class AttributesTable
def html_row(attribute)
row(attribute){ |model| model[attribute].html_safe }
end
def bool_row(attribute)
row(attribute){ |model| model[attribute] ? '✔'.html_safe : '✗'.html_safe }
end
end
end
end

Finally we can make the change in the Active Admin View now and we will replace column with html_column or bool_column as per requirement.


ActiveAdmin.register Post do
index do
selectable_column
html_column :comment
html_column :description
bool_column: isPrivate
column :website_url
actions
end
end

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: