Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
How to use constants defined in javascript in an erb file as an argument in rails api method

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!