3

I am trying to follow this example to embed Ruby code in my application.js How do I properly put embedded ruby code in to JavaScript?

However when I put the line:

var formData = <%= @s3_direct_post.fields.to_json.html_safe %>;

I get "SyntaxError: expected expression, got '<'"

I've seen advice on other similar questions to put quotes around the Ruby code like so:

var formData = '<%s3_direct_post.fields.to_json.html_safe %>';

but then the variable becomes the string <%s3_direct_post.fields.to_json.html_safe %> instead of executing the Ruby and putting the result in a string.

FYI I'm following a tutorial (https://devcenter.heroku.com/articles/direct-to-s3-image-uploads-in-rails) so it's possible that I didn't set something up right.

shivam
  • 16,048
  • 3
  • 56
  • 71
Pepperfudge
  • 103
  • 6

3 Answers3

1

You can't simply use ruby code or expression inside a javascript file, you need to first preprocess ruby code and then pass on that value to javascript engine for processing. Just make sure that your file has js.erb extension, doing so your file will be first processed for ruby expressions and then for js.

For further details you could refer to this question

Community
  • 1
  • 1
Mandeep
  • 9,093
  • 2
  • 26
  • 36
0

I believe the issue you are running into is that Rails does not attempt to evaluate application.js and just delivers the file "as is". The tutorial you are referencing does not explicitly state this but you have to place any Ruby scriptlets into ERB templates. E.g. try adding your code to the app/views/users/_form.html.erb or the new.html.erb template instead of application.js. Rails will interpret the Ruby code and render the the substituted value.

0

If you want to use javascript code in your views you can add below code to your page end. And you should be able to run javascript code

<% content_for :javascript do %>
    $(). //  your ruby code e.g. var formData = #{@s3_direct_post.fields.to_json.html_safe};
<% end %>

Or Suppose you have show action in your controller and show form in views, then you can create show.js.html file and write java-script code in that

Sonalkumar sute
  • 2,565
  • 2
  • 17
  • 27