Reputation: 31
I know that there's quite a lot of gems that do the job, but I think it's quite excessive to use a whole gem for such an easy task.
I found that js does it pretty easy:
Intl.DateTimeFormat().resolvedOptions().timeZone
The answer is a string like "Europe/Moscow"
.
We can easily save it to db
create_table :users do |t|
t.string :time_zone, default: "UTC"
...
end
and set user's time zone like:
# app/controllers/application_controller.rb
around_action :set_time_zone, if: :current_user
private
def set_time_zone(&block)
Time.use_zone(current_user.time_zone, &block)
end
So my question is: Am I missing something important (why these gems are being used) or I can do it like I wrote above (without any gems)?
Inspired by the ThoughtBot's article and this question
Upvotes: 3
Views: 518
Reputation: 74
You're not missing anything important. Every language has different kinds and numbers of bells and whistles adorning its basic parts. The specification for "ECMAScript Internationalization API" (what gives you the power to write Intl.DateTimeFormat().resolvedOptions().timeZone
) wasn't introduced until 2012, some years after JavaScript was first conceived.
Somewhat similarly on the back end, the Rails framework provides its own API baked in, allowing you to create Time
instances with the added accuracy and functionality of the TZInfo
gem thanks to Rails' ActiveSupport::TimeZone
wrapper. You don't even have too stray to far from what you might be used to in Ruby, intuitively calling both Time
and TZInfo
methods on Time
in Rails.
The code you wrote above technically relies on a gem. Rails is a gem! Maybe the delineation you're going for is whether we should use libraries that come with our languages and frameworks or reach out for new ones. That difference is not as important as how dependable the libraries are in the first place. So you aren't missing anything! It's just a jungle out there :)
Upvotes: 1