Peter Nixey
Peter Nixey

Reputation: 16565

Can you generate routes for an Angular app on a Rails server without duplicating logic?

We've got an angular application together with Angular routing. However we need to do things like sending out links in emails or via Twitter. These have to be done from the server that requires routes to be generated server-side

This means that we either need to duplicate the routing logic and path helpers currently contained in our Angular routing file or find a way to parse the Angular routing file on the server and then generate ruby path_helper methods.

Is there an easy way to do this - some Rails plugin or similar?

Edit (to clarify)

I need to be able to generate links to pages on the server and during cron jobs. If this were a rails app I would be able to use path helpers like edit_user_path @user.

The problem is that the logic for the routing is now in Angular. So there's no way to generate paths on the rails side. I need some way to do that. It can't be done from the client as the client won't be present - this could be activated from a cron job

Upvotes: 5

Views: 389

Answers (2)

Andrew
Andrew

Reputation: 151

There's a nice Rails gem called JSRoutes that we use in our BackboneJS/Rails project. It allows you to expose a custom subset of your Rails routes to the frontend application. I'd suggest checking it out, let me know if you'd like more concrete examples - I'd rather let their docs do the talking.

Upvotes: 0

user9903
user9903

Reputation:

I'm assuming that you want a user to be able to hit myapp.com/something/unique-333/ as a url.

Instead of replicating routes you would have a controller that's assigned to the URL's prefix to handle it. The controller would check the suffix of the URL (/unique-333) and do whatever it needs to do that's specific to that url.

If you want to share this between your backend and frontend, you can do that by storing the URL prefix in the backend and on the frontend you would grab it right after the service is initialized and update the router.

It would look something like this:

/* REST API */
function get_url_prefix() {
  return '/something/';
}
function get_obj() {
  return JsonResponse({
    'data': obj,
    'url': get_url_prefix() + obj.id + '/';
  });
}

and on the frontend in AngularJS:

.config(function($routeConfig, restApi) {
  restApi.get_url_prefix().then(function(urlPrefix) {
    $routeConfig = {
      urlPrefix: CtrlToHandleUniqueRoutes
    };
  });
});

Your controller basically functions as a router for unique urls. Notice that the unique url lives completely in the backend.

Upvotes: 1

Related Questions