I'm trying to play around with my code and I have hit a
I have a script tag in an erb file. I get the browser timezone and store it in a constant. I want to use the value of the constant in a rails API method as an argument but I get the error
undefined local variable or method `browser_time_zone' for #
<script>
// this returns Eastern Time (US & Canada)
const browser_time_zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const timezone = <%= ActiveSupport::TimeZone::MAPPING.key(browser_time_zone) %>
</script>
How can I use the value of browser_time_zone as an argument to the TimeZone Mapping method? Any help will be appreciated
I don't think you can do what you want, because the execution of the Javascript and Ruby happen at different times (Ruby first when the page is being rendered/created, then javascript when the browser loads the HTML). Instead, you could try something like this:
<script>
// this returns Eastern Time (US & Canada)
// https://stackoverflow.com/a/28191966/2543424
function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
const time_zone_mapping = <%= ActiveSupport::TimeZone::MAPPING.to_json.html_safe %>;
const browser_time_zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const timezone = getKeyByValue(time_zone_mapping, browser_time_zone);
</script>
Here we are dumping the contents of ActiveSupport::TimeZone::MAPPING to a new javascript variable in the form of a JSON object, and then accessing it in much the same way as what you were trying to do, but all via Javascript.
Note, the ActiveSupport::TimeZone::MAPPING.to_json.html_safe syntax may not be 100% correct, but that's the general idea