0
votes

I have Grape based API set up in a Rails 4 app. I want to render the json produced by one of the API calls into a view in an inline tag - specifically to make JSON data available to an angularjs view to avoid a (JSON API) call to server after page load.

Any ideas how to get a Grape API rendered to string?

/app/api/api.rb

class API < Grape::API
  version 'v1', using: :path
  format :json
  get '/dashboard' do
    ...
  end
end

views/dashboard/index.html.erb

<script>   
  <%= render some-way-to-render-to-text('/api/v1/dashboard.json') %>
</script>

I could use a get http request to get it rendered, but I am hoping to avoid the overhead of the http call. I rather call the API class directly.

1
Please explain why would you want to do that, sounds kind of weird.Nicolas Garnil
Optimization. The dashboard page is built using angular.js - first thing it does is to request dashboard.json from server and generate/render view using the data returned. But that causes one extra server request and slows down the page rendering. I want to render the json data inline when the page gets rendered and use ng-init so angular.js doesn't have to call for dashboard.json. Again, this is an optimization to improve first page load experience.amolk

1 Answers

0
votes

Your erb file gets rendered into raw html before it gets sent to the client. Your api call is made after this, so there's no way of receiving an http response and processing it in ruby, because by this point all of the ruby has been translated into html.

What you want to do is process it in angular. From there you could use jquery to insert it into the DOM.

In angular you would do something like the following in the service:

$http.get(....).success(//insert into DOM here)