I was working on a project that is hosted on a different time zone from where I am. The server is located in Asia while I reside in the US time zone. As part of the Capistrano deployment process, I use deploy:web:disable to disable the site with a maintenance message while the deployment is running. What the deploy:web:disable does is copying the file “maintenance.html” across to the server in the specified location. And the webserver has been previously configured to detect this file and if found, serves it to the user, while the Rails site remains temporarily disabled during the deployment process.
This works great except for one small significant detail. Before the maintenance.html file is copied over to the server, it is parsed and the current time is inserted as part of the text, to inform the user of the time the server went down for maintenance. The issue was that the time inserted is always in the EDT time zone (where I am at), even though my Rails app has been configured for the actual location of the server. The reason for this is simple – the maintenance.html.erb was parsed in my local time zone, and hence the local time was inserted as a result. This can become confusing to users to see the time in EDT while they are in the Asian time zone.
In the Rails console, I could just do a Time.zone.now and it gives me the actual remote time of the server, since my Rails app is already configured for that time zone. So I inserted the same code into the maintenance file <%= Time.zone.now.strftime(%H %M) %>. However during deployment I would get an error message about the unrecognized zone method for Time. After hours of testing and Googling, I came to understand the cause of this issue – the code works in the Rails console because the Rails environment was already loaded. But this is not the case during deployment. Apparently Rake does not load the Rails environment and works purely as a Ruby environment.
To overcome this, I have to install the tzinfo gem (include it in my Gemfile as part of the development group and run Bundle install). Then include the line: require ‘tzinfo’ in my deploy.rb file. Finally in my maintenance.html.erb template file I include the following lines:
<% tz = TZInfo::Timezone.get(‘Asia/City_Name’) %>
<%= tz.now.strftime(“%b %d, %Y – %H:%M”) %> to display the local time.
Problem solved. The time displayed in the Maintenance.html file is now in remote time, which is now more meaningful to the local users.