Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change how ActiveAdmin displays time (every time)

Since the default time in the database is in utc, I wanted to be able to still display it in the users correct time. To do this I had to take column :created_at and change it into this:

index do
...
  column :created_at, :sortable => :created_at do |obj|
    obj.created_at.localtime.strftime("%B %d, %Y %H:%M)
  end
...
end

Seems pretty easy to do once or twice, but when you need to override every index and show method, the process get's a little taxing.

Is there a way to override how ActiveAdmin displays time without having to override each occurrence?

I know I could create a function or probably use the functions provided for time better, but I'd still have to use it each time I want to display time. I want to override it without worrying I missed one.

like image 498
Tom Prats Avatar asked Jul 24 '13 22:07

Tom Prats


2 Answers

You can target just ActiveAdmin by telling it to always use a particular filter in config/initializers/active_admin.rb , by adding a line like this:

config.before_action :set_admin_timezone

(or config.before_filter :set_admin_timezone for versions of Rails before Rails 4)

Then in your ApplicationController, you can just define the method set_admin_timezone, and ActiveAdmin will use it. For example:

def set_admin_timezone
  Time.zone = 'Eastern Time (US & Canada)'
end

You should be able look up the current admin user in that method (in order to get their particular timezone), but I haven't tried that.

like image 56
Melinda Weathers Avatar answered Oct 18 '22 22:10

Melinda Weathers


I've found there are two ways to do this:

1. Javascript

This is the easier method because it is very short and doesn't involve adding a db field. It works because it uses the users timezone from their browser. This answer gives insight on how to do this.

2. From the Database

This process can be found in this railscast.

Essentially store a time_zone field in the users table. Then use an before_filter (although an around_filter might be a better idea) to set the timezone in the controller.

before_filter :set_time_zone

private
def set_time_zone
  Time.zone = current_user.time_zone if current_user
end
like image 25
Tom Prats Avatar answered Oct 18 '22 22:10

Tom Prats