Reputation: 1336
This code is executed from a view, and it works:
<% @metaTags = OpenGraph.fetch('http://www.someurl.com') || nil %>
<% if @metaTags != nil %>
postTitle = truncateStr('<%= @metaTags.title %>', 72);
<% end %>
I'd like to do the same but passing http://www.someurl.com
as a javascript-computed parameter, like this
var someURL = ... (compute value);
setCookie("someURL", someURL, 10000);
<% @metaTags = OpenGraph.fetch(cookies[:someURL]) || nil %>
<% if @metaTags != nil %>
postTitle = truncateStr('<%= @metaTags.title %>', 72);
<% end %>
It doesn't work.
var someURL = ... (compute value);
setCookie("someURL", someURL, 10000);
<% readPostURL %>
<% if @metaTags != nil %>
postTitle = truncateStr('<%= @metaTags.title %>', 72);
<% end %>
and in controller
private
def readPostURL
@metaTags = OpenGraph.fetch(cookies[:postURL]) || nil
end
helper_method :readPostURL
It doesn't work either.
Both scenarios seem to have troubles with the cookies. Is there a way to run OpenGraph.fetch(parameter) from a view with some javascript variable
?
Upvotes: 0
Views: 91
Reputation: 4296
This is a common issue for experienced developers that are new to web development. Since the JavaScript runs in the browser, it actually executes a (relatively) long time after the Ruby code has finished.
Here's an abridged version of the HTTP request/response cycle:
The solution is typically pretty simple: make a second request after your JavaScript has run. You have a lot of options for how to make the second request based on your particular application (redirect, refresh, AJAX).
As for your actual code, the cookie approach is good if you want to keep the information around for future requests. If you only need it once, just stick the data in a URL parameter for your second request.
Upvotes: 1
Reputation: 2674
You can't mix Javascript-computed stuff into your Ruby code easily like that. You could probably use something like ExecJS to call Javascript code server-side from your Ruby, but that would not be view code. And it would probably be more trouble than it's worth.
Your options are:
someURL
in Ruby when you're rendering the viewUpvotes: 1