Sachin R
Sachin R

Reputation: 11876

Ruby object in my JavaScript file

I have a Ruby object and I want to use that object in JavaScript. I haven't seen that type of thing, but I want a Ruby object in my .js file.

Is this possible? Thanks in advance

Upvotes: 0

Views: 327

Answers (3)

John Topley
John Topley

Reputation: 115292

You can't use Ruby objects within JavaScript because Ruby code executes on the server and JavaScript executes within the client Web browser. However, you can execute Ruby code and then use the results within JavaScript as Mark illustrates in his answer to your question.

Upvotes: 0

mark
mark

Reputation: 10564

You can only pass strings, json or xml. Though, you can do it without ajax.

# dynamic_data.js.erb

var js_data = <%= Time.now.to_s -%> 

# show.html.erb

render :partial => 'dynamic_data'

or

- content_for :head do
    = javascript_tag "var js_data = #{ Time.now.to_s };"

Upvotes: 1

Daniel O&#39;Hara
Daniel O&#39;Hara

Reputation: 13428

No, you can't use your Ruby objects in JavaScript. You can, however, request any data encoded with JSON or XML (even plain text or your own data format) from the server-side using AJAX.

Upvotes: 3

Related Questions