ruby-on-railshelpermethods

Executing ruby code from a view in rails


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.comas a javascript-computed parameter, like this

Attempt 1

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.

Attempt 2

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?


Solution

  • 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:

    1. Browser makes a request to the server
    2. Server parses the request
    3. Server generates the response (this is where your Ruby code is running)
    4. Browser receives the response
    5. Browser renders response (this is where your JavaScript code is running)

    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.