Skip to content

Instantly share code, notes, and snippets.

@geelen
Created April 8, 2013 01:46
Show Gist options
  • Save geelen/5333584 to your computer and use it in GitHub Desktop.
Save geelen/5333584 to your computer and use it in GitHub Desktop.
My way for including Rails' CSRF token in AngularJS client code
# Set up the application
app = angular.module('ratingRampage', [])
# This is an injectable property
app.value 'Authentication', {}
# Add a directive so that if we see a csrf-token attribute, this gets set
app.directive 'csrfToken', (Authentication) ->
(scope, element, attrs) ->
Authentication.csrf_token = attrs.csrfToken
# Some service, which needs to make a POST request
app.factory 'Rating', ($http, Authentication) ->
class Rating
constructor: (@film) ->
save: (rating) ->
# Add the authenticity_token as a POST param
$http.post(@film.rating_url,
authenticity_token: Authentication.csrf_token,
rating: rating
).success => @saved()
saved: -> #...
<div ng-app="ratingRampage' csrf-token="<%= form_authenticity_token %>">
<!-- Your app code goes here -->
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment