Skip to content

Instantly share code, notes, and snippets.

@anamartinez
Created January 22, 2014 21:53
Show Gist options
  • Save anamartinez/8568103 to your computer and use it in GitHub Desktop.
Save anamartinez/8568103 to your computer and use it in GitHub Desktop.
Time zone select rails helper with formatted offset
<%= f.time_zone_select :time_zone, TimeZoneWithFormattedOffset.all.sort_by { |tz| [tz.now.utc_offset, tz.name] } %>
class TimeZoneWithFormattedOffset < ActiveSupport::TimeZone
def to_s
"(GMT#{self.now.formatted_offset}) #{self.name}"
end
end
@arielvalentin
Copy link

I am curious, has this solution worked long term for you or did you find something else?

@dduqueti
Copy link

dduqueti commented Jul 19, 2018

I get this
NoMethodError (undefined method `[]' for nil:NilClass)` on `ruby-2.5.0/gems/activesupport-4.2.10/lib/active_support/values/time_zone.rb:243:in `[]'
when trying to use TimeZoneWithFormattedOffset.all. Maybe things have changed a lot since.

@dduqueti
Copy link

dduqueti commented Jul 19, 2018

For whoever tries to use this, this works very well! After spending hours of debugging I noticed I had to add this to the custom class:

class TimeZoneWithFormattedOffset < ActiveSupport::TimeZone
  @lazy_zones_map = ThreadSafe::Cache.new

  def to_s
    "(GMT#{self.now.formatted_offset}) #{self.name}"
  end
end

Don't know why @lazy_zones_map wasn't instantiated which generated an exception when running all -> zones_map

@msumit
Copy link

msumit commented Dec 20, 2018

@dduqueti, thanks a ton man, spent hours in debugging the same issue and wasn't able to figure out why the @lazy_zones_map is empty and throwing errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment