Unless you’ve been completely disconnected from tech news for the last 2 years, you probably heard about AngularJS and how badass it is (or how it’s complete shit). If you’re a Rails developer, you’re probably tempted to just include it into a rails application. Here are some things to consider before you do this:
When you should do this
- You want some of your application to be handled by Rails, while you want other parts require to be a bit more dynamic
- You currently have a Ruby on Rails application and you want to slowly migrate the view part to AngularJS
When you really shouldn’t
- You want your application to be a full Single Page App and you want to use Rails as your API
- You already know Ruby on Rails, so you think it will be easier to do it like this
If you fall into the second category, I highly suggest you set up your application as a separate project using an AngularJS yeoman template. Not only will it be cleaner, but it will allow you to use a lot of the node.js based tools like bower and gulp.
You could still use those inside a Rails app, but they are not built to work together.
Now the good parts
Good, so you’re a good match for this combo. Let’s get to the meaty parts.
First of all, the routing will be handled by your AngularJS app, so you need to redirect any path under that namespace to your angular app.
# The root path get "/angularjs", to: "angularjs#index" # Redirect any requests to other paths to get "/angularjs/*path", to: "angularjs#index"
This means that requests to http://yourwebsite.com/angularjs/customers/5 will be redirected to the same view, so your AngularJS router can pick it up and deal with it.
Rails typically does nothing here. This is all you need:
class AngularjsController < ApplicationController def index end end
//= require angularjs_app/init.js //= require angularjs_app/module1/index.js //= require angularjs_app/module/2
angular.module("myapp", [ "ngRoute", "ngResource", // ... ]);
And that’s it!
You can treat it as any other AngularJS app. Put your code into modules so you can pop features in and out and you can freely use Ruby on Rails everywhere else in your app. The other beautiful thing about it is that you’re serving your AngularJS app on the same domain as your API, so you don’t need to worry about CORS.
I hope this post helps you out. Feel free to leave some comments below!