0

I try to store a token in my localstorage from a ruby variable, As I understood, you can only set LocalStorage with Javascript, So here is my question, how can I pass my variable from Ruby to Javascript ? I saw some answers with script tag in the view, but is there any solution to do it directly in the app.js folder ?

So here is my Controller :

 @token = HTTParty.post('https://test.pro/2.0/auth/token/access', 
      body: {
          client_id: XXX,
          client_secret: "YYYYYYYYYYYYYY",
          code: LLLLLL
      }
  )

And in my view if I do a <%= @token %>, I have the following result :

{"access_token": "1VwCAjhsfCsdEoBoQs1G9kLHKoWOcJjamyj1s8_NQPrHeGNagzYYFrXKp_VlY", "token_type": "Bearer"}

Thanks for your help !

1 Answer 1

2

If you want to perform javascript from within a ruby file you can use a javascript_tag:

https://apidock.com/rails/ActionView/Helpers/JavaScriptHelper/javascript_tag

An example of how to use it:

Accessing Ruby objects in javascript

In your case, something in your view like:

<% javascript_tag do %>
   localStorage.setItem('accessToken', <%= @token["access_token"] %>);
   localStorage.setItem('tokenType', <%= @token["access_token"] %>);
<% end %>

Should do the trick

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.