Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda