browser-timezone-rails icon indicating copy to clipboard operation
browser-timezone-rails copied to clipboard

Question: How to use with Rails 6 and Webpacker?

Open coezbek opened this issue 3 years ago • 2 comments

When using Rails 6 with Webpacker for application.js, my attempts to use require the javascript dependencies have failed. Do you think you will unbundle the Javascript and support adding the JS dependencies via yarn?

coezbek avatar Mar 23 '21 16:03 coezbek

I got around this adding sprockets back alongside my existing Webpacker setup.

  1. Add //= link_directory ../javascripts .js to app/assets/config/manifest.js
  2. Create app/assets/javascripts/application.js and add the two //=require lines for this gem
  3. Add javascript_include_tag alongside javascript_path_tag in <head>

pooriajr avatar Apr 25 '21 21:04 pooriajr

Sorry for not advertise this gem, but you can achieve this functionality by adding a package

yarn add js-cookie

and create javascript file

// app/javascript/browser_timezone_cookie.js
import Cookies from 'js-cookie'

// https://github.com/kbaum/browser-timezone-rails/blob/master/app/assets/javascripts/browser_timezone_rails/set_time_zone.js.erb
Cookies.set(
 "browser.timezone",
  Intl.DateTimeFormat().resolvedOptions().timeZone,
  {
    expires: 365,
    path: '/'
  }
);

include it in main application pack file

// app/javascript/packs/application.js
import 'browser_timezone_cookie'

and use the cookie in around action in application controller

# app/controllers/application_controller.rb
  prepend_around_action :use_time_zone
  def use_time_zone(&action)
    Time.use_zone(Time.find_zone(cookies['browser.timezone'].presence) || Time.zone, &action)
  end

duleorlovic avatar Sep 08 '21 10:09 duleorlovic